@noego/trust 0.5.1-dev.3 → 0.5.1-dev.4

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/baseline-command.ts","../../src/cli/native-check.ts","../../src/cli/native-engine.ts","../../src/cli/check-command.ts","../../src/cli/run-lock.ts","../../src/cli/explain.ts","../../src/cli/refactor-command.ts","../../src/core/call-graph.ts","../../src/core/change.ts","../../src/core/import-graph.ts","../../src/core/refactor-plan.ts","../../src/cli/index.ts"],"sourcesContent":["// `trust baseline [paths…] [--update] [--tsconfig <path>] [--root <dir>]` — runs the native engine\n// (as `trust check` does, without the strict rules) over the files `trust check` resolves, and compares\n// the findings against trust-baseline.json (file + rule + origin → count). Files in the config's\n// `ignore` zone are skipped. With named paths only the checked files' entries can go stale or be\n// rewritten by --update; with no paths the run covers the whole baseline.\nimport { existsSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport {\n compareToBaseline,\n describeBaselineDelta,\n readBaseline,\n serializeBaseline,\n updateBaseline,\n WHOLE_BASELINE,\n type BaselineScope,\n} from '../core/baseline.js';\nimport { emptyTrustConfig } from '../core/check-file.js';\nimport { BOUNDARY_RULE, DROPPED_RESULT_RULE, TYPE_CLAIM_RULE, UNTRUSTED_VALUE_RULE } from '../core/messages.js';\nimport { loadTrustConfig } from '../eslint/config.js';\nimport { Zones } from '../eslint/zones.js';\nimport { checkNative } from './native-check.js';\nimport { logUnmatchedGlobs, logWalkFailure, relativeTo, resolveFiles } from './source-files.js';\n\nexport interface BaselineCommandOptions {\n readonly cwd: string;\n /** Files or directories; the current directory when empty. */\n readonly paths: readonly string[];\n readonly configFile: string;\n readonly baselineFile?: string;\n readonly update: boolean;\n /** One tsconfig for every file, instead of the config's `tsconfig` entries or the nearest tsconfig.json. */\n readonly tsconfig?: string;\n /** Directory the config's paths resolve against, instead of the config file's directory. */\n readonly root?: string;\n readonly log: (line: string) => void;\n}\n\n/** The baseline's counts (none when the file does not exist), or why it could not be read. */\nexport { readBaseline };\n\n/** Returns the process exit code: 0 ok, 1 new violations, 2 could not run (TypeScript, an unloadable file, an unreadable baseline). */\nexport async function runBaselineCommand(options: BaselineCommandOptions): Promise<number> {\n const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ['.']);\n if ('missing' in resolved) {\n options.log(`trust baseline: no such file or directory: ${resolved.missing}`);\n return 2;\n }\n const configPath = resolve(options.cwd, options.configFile);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = existsSync(configPath)\n ? loadTrustConfig(configPath, { rootDir })\n : emptyTrustConfig(rootDir ?? options.cwd);\n logUnmatchedGlobs(options.log, 'baseline', config);\n const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, 'trust-baseline.json'));\n const zones = new Zones(config.rootDir, config.passthrough, config.ignore);\n const files = resolved.files.filter((file) => zones.zoneOf(file) !== 'ignore');\n // With named paths the run speaks only for the files it checked; with none it covers the whole tree.\n const scope: BaselineScope =\n options.paths.length === 0 ? WHOLE_BASELINE : { kind: 'files', files: new Set(files.map((file) => relativeTo(config.rootDir, file))) };\n\n // The native engine holds one compact program instead of TypeScript's (several GB on a large repo).\n const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };\n const { findings, walk } = await checkNative({ cwd: options.cwd, files, config, programs, strictFiles: [], log: options.log });\n if (walk.status !== 'ok') {\n logWalkFailure(options.log, 'baseline', walk);\n return 2;\n }\n\n // A whole-tree --update rewrites the file from scratch (and so also repairs an unreadable one).\n const baseline = options.update && scope.kind === 'all' ? { counts: {} } : readBaseline(baselineFile);\n if ('error' in baseline) {\n options.log(`trust baseline: could not read the baseline: ${baseline.error}`);\n return 2;\n }\n if (options.update) {\n const updated = updateBaseline(baseline.counts, findings, scope);\n writeFileSync(baselineFile, serializeBaseline(updated.counts));\n const kept = updated.kept > 0 ? ` Kept the entries of ${updated.kept} unchecked file(s).` : '';\n options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${files.length} checked file(s).${kept}`);\n return 0;\n }\n const { added, stale } = compareToBaseline(findings, baseline.counts, scope);\n if (stale.length > 0) {\n options.log(`${stale.length} baseline entr${stale.length === 1 ? 'y has' : 'ies have'} fewer findings now; run with --update to shrink the baseline.`);\n }\n if (added.length === 0) {\n options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${files.length} file(s)).`);\n return 0;\n }\n const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);\n options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);\n for (const delta of added) for (const line of describeBaselineDelta(delta)) options.log(` ${line}`);\n options.log('Guard each call (try/catch returning Result.err, or Trust.try), or trust its origin in trust.config.json.');\n const hasTypeClaims = added.some((delta) => delta.rule === TYPE_CLAIM_RULE);\n if (hasTypeClaims) options.log('Prove each claimed type (narrow or validate the value) instead of asserting it.');\n const hasUntrustedValues = added.some((delta) => delta.rule === UNTRUSTED_VALUE_RULE);\n if (hasUntrustedValues) {\n options.log('Validate each untrusted value (or keep it as `unknown` and narrow it), or add its origin to \"trust_type\" in trust.config.json.');\n }\n if (added.some((delta) => delta.rule === DROPPED_RESULT_RULE)) {\n options.log('Return each dropped failure (`if (!r.ok) return r;`) or handle it with Trust.decide.');\n }\n if (added.some((delta) => delta.rule === BOUNDARY_RULE)) {\n options.log('Decide every kind at each boundary (an exhaustive `switch`) and return plain data, or exclude it under \"boundaries\" in trust.config.json.');\n }\n const alsoShows = `${hasTypeClaims ? ', and why a line is a type claim' : ''}${hasUntrustedValues ? ', and where an untrusted value comes from' : ''}`;\n options.log(`\\`trust explain <file>:<line>\\` shows which origin a call resolves to${alsoShows}.`);\n return 1;\n}\n","// Default `trust check` engine. Node resolves files, trust config and strict files; Rust owns\n// tsconfig parsing, embedded standard libs, program construction and rules. One JSON request/reply.\n//\n// Two builds speak the same protocol: a platform binary from an optional npm package (preferred),\n// and the bundled Wasm fallback. Neither requires an end-user Rust toolchain or postinstall download.\n// Explicit TRUST_NATIVE_BIN / TRUST_NATIVE_WASM overrides and local development builds still work.\n// TRUST_NATIVE_ENGINE=wasm|binary forces one.\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { prepareSvelte, SvelteFileError, SvelteInputs } from '../core/svelte.js';\nimport { groupByTsconfig } from '../core/program.js';\nimport { loadTypeScript } from '../eslint/typescript.js';\nimport { decide } from '../eslint/policy.js';\nimport { spawnSync } from 'node:child_process';\nimport { Worker } from 'node:worker_threads';\nimport { nativeEngine } from './native-engine.js';\n\nimport type { Finding } from '../core/messages.js';\nimport { isRuleEnabled, type OptInRule, type TrustConfig } from '../eslint/config.js';\n\nimport { relativeTo, type ProgramOptions, type ProgramWalk } from './source-files.js';\n\nexport { nativeBinary, nativeWasm, nativeEngine, type NativeEngine } from './native-engine.js';\nexport const NATIVE_PROTOCOL_VERSION = 5;\n\n/** Stack of the wasm run's worker thread, in MB: the checker recurses deeply (ts-rust's own host uses 256). */\nconst WASM_STACK_SIZE_MB = 256;\n\nconst OPT_IN_RULES: readonly OptInRule[] = [];\n\ninterface NativeResponse {\n readonly version: number;\n readonly findings: readonly Finding[];\n readonly errors: readonly string[];\n readonly setupError: string | null;\n readonly stats: { readonly loadSeconds: number; readonly checkSeconds: number; readonly checkedFiles: number };\n}\n\nexport interface NativeCheckOptions {\n readonly cwd: string;\n /** Absolute paths of the files to check (already filtered by the ignore zone). */\n readonly files: readonly string[];\n readonly programs: ProgramOptions;\n readonly config: TrustConfig;\n /** Absolute paths of the files the strict rules also run on. */\n readonly strictFiles: readonly string[];\n readonly perf?: boolean;\n readonly log: (line: string) => void;\n}\n\ninterface EngineRun {\n /** 0: `output` is the JSON response. Else `output` (or `stderr`) says what went wrong. */\n readonly status: number;\n readonly output: string;\n readonly stderr: string;\n}\n\nfunction runBinary(binary: string, request: string, cwd: string): EngineRun {\n const result = spawnSync(binary, [], { cwd, input: request, encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024 });\n if (result.error) return { status: -1, output: `trust-native could not run: ${result.error.message}`, stderr: '' };\n if (result.status !== 0) {\n return { status: result.status ?? -1, output: `trust-native exited with ${result.status ?? result.signal}: ${result.stderr.trim().split('\\n').slice(0, 5).join('\\n')}`, stderr: result.stderr };\n }\n return { status: 0, output: result.stdout, stderr: result.stderr };\n}\n\nfunction runWasm(wasmPath: string, request: string): Promise<EngineRun> {\n return new Promise((resolvePromise) => {\n const worker = new Worker(new URL('./wasm-worker.js', import.meta.url), {\n workerData: { wasmPath, request },\n resourceLimits: { stackSizeMb: WASM_STACK_SIZE_MB },\n });\n let result: EngineRun | undefined;\n worker.on('message', (message: { status: number; output: string; stderr: string }) => {\n result = message.status === 0 ? message : { status: message.status, output: `trust-native (wasm) failed with ${message.status}: ${message.output.trim().split('\\n').slice(0, 5).join('\\n')}`, stderr: message.stderr };\n });\n worker.on('error', (error) => {\n result ??= { status: -1, output: `trust-native (wasm) crashed: ${error.message}`, stderr: '' };\n });\n worker.on('exit', (code) => {\n resolvePromise(result ?? { status: -1, output: `trust-native (wasm) worker ended without a result (exit ${code})`, stderr: '' });\n });\n });\n}\n\n/** Reject stale engines and malformed/partial output rather than reporting a false clean check. */\nexport function validResponse(value: unknown): value is NativeResponse {\n if (!value || typeof value !== 'object') return false;\n const response = value as Record<string, unknown>;\n if (response.version !== NATIVE_PROTOCOL_VERSION || !Array.isArray(response.findings) || !Array.isArray(response.errors)) return false;\n if (response.setupError !== null && typeof response.setupError !== 'string') return false;\n if (!response.errors.every(error => typeof error === 'string')) return false;\n if (!response.findings.every(finding => finding && typeof finding === 'object'\n && ['file', 'rule', 'origin', 'message'].every(key => typeof finding[key] === 'string')\n && Number.isInteger(finding.line) && finding.line > 0 && Number.isInteger(finding.column) && finding.column > 0\n && (finding.severity === 'error' || finding.severity === 'warning'))) return false;\n const stats = response.stats as Record<string, unknown> | undefined;\n return !!stats && ['loadSeconds', 'checkSeconds', 'checkedFiles'].every(key => typeof stats[key] === 'number' && Number.isFinite(stats[key]) && (stats[key] as number) >= 0);\n}\n\n/** One request to the native engine; the findings come back unsorted. */\nexport async function checkNative(options: NativeCheckOptions): Promise<{ findings: Finding[]; walk: ProgramWalk }> {\n const { config } = options;\n if (options.files.length === 0) return { findings: [], walk: { status: 'ok' } };\n for (const rule of OPT_IN_RULES) {\n if (isRuleEnabled(config, rule)) {\n return { findings: [], walk: { status: 'setup-failed', message: `the native engine does not support the \"${rule}\" rule yet; this release cannot check this configuration safely` } };\n }\n }\n const engine = nativeEngine();\n if (!engine) {\n return {\n findings: [],\n walk: {\n status: 'setup-failed',\n message: 'the trust-native engine is missing: reinstall @noego/trust (it includes a Wasm fallback), unset TRUST_NATIVE_ENGINE if it forces an unavailable binary, or set TRUST_NATIVE_BIN / TRUST_NATIVE_WASM; for a checkout, build the engine in native/',\n },\n };\n }\n\n let svelte: ReturnType<typeof prepareSvelte>;\n let extraRoots: Record<string, string[]>;\n try {\n const needed = options.files.some(file => file.endsWith('.svelte') || readFileSync(file, 'utf8').includes('.svelte'));\n if (!needed) { svelte = new SvelteInputs(); extraRoots = {}; }\n else {\n const ts = loadTypeScript(options.cwd);\n svelte = prepareSvelte(ts, options.cwd, options.files, options.programs.tsconfig, options.programs.mappings);\n const grouping = groupByTsconfig(ts, options.cwd, options.files, options.programs.tsconfig, options.programs.mappings);\n if (grouping.kind !== 'grouped') return { findings: [], walk: { status: 'setup-failed', message: grouping.message } };\n extraRoots = Object.fromEntries([...grouping.groups].map(([owner, files]) => [owner ?? '', svelte.extraRoots(files)]));\n }\n } catch (error) {\n return { findings: [], walk: error instanceof SvelteFileError ? { status: 'file-errors', errors: [error.message] } : { status: 'setup-failed', message: error instanceof Error ? error.message : String(error) } };\n }\n const request = JSON.stringify({\n version: NATIVE_PROTOCOL_VERSION,\n cwd: options.cwd,\n rootDir: config.rootDir,\n files: options.files.map(file => svelte.generated(file)),\n virtualFiles: Object.fromEntries(svelte.virtual),\n virtualPaths: Object.fromEntries(svelte.paths),\n extraRoots,\n programs: options.programs,\n perf: options.perf ?? false,\n rules: { trustedState: isRuleEnabled(config, 'trusted-state'), typeClaim: isRuleEnabled(config, 'type-claim'), untrustedValue: isRuleEnabled(config, 'untrusted-value'), untrustedCallbacks: config.rules.untrustedCallbacks, droppedResult: isRuleEnabled(config, 'dropped-result'), redundantGuard: isRuleEnabled(config, 'redundant-guard'), resultLookalike: config.rules['result-lookalike'] },\n config: {\n levels: config.levels.map((level) => ({ source: level.source, trust: level.trust, distrust: level.distrust, typeTrust: level.typeTrust, typeDistrust: level.typeDistrust })),\n passthrough: config.passthrough.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns })),\n ignore: config.ignore.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns })),\n boundaries: config.boundaries.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns, index: group.index, exclude: group.exclude })),\n },\n strictFiles: options.strictFiles.map(file => svelte.generated(file)),\n });\n const started = Date.now();\n const result = engine.kind === 'binary' ? runBinary(engine.path, request, options.cwd) : await runWasm(engine.path, request);\n if (result.status !== 0) {\n return { findings: [], walk: { status: 'setup-failed', message: result.output } };\n }\n let response: NativeResponse;\n try {\n const value: unknown = JSON.parse(result.output);\n if (!validResponse(value)) throw new Error('Invalid engine response');\n response = value;\n } catch {\n return { findings: [], walk: { status: 'setup-failed', message: `trust-native (${engine.kind}) returned malformed output` } };\n }\n if (process.env.TRUST_NATIVE_DEBUG) {\n options.log(\n `trust native: ${engine.kind} engine checked ${response.stats.checkedFiles} file(s): load ${response.stats.loadSeconds.toFixed(1)}s, ` +\n `rules ${response.stats.checkSeconds.toFixed(1)}s, round trip ${((Date.now() - started) / 1000).toFixed(1)}s`,\n );\n if (result.stderr.trim()) options.log(result.stderr.trim());\n }\n if (response.setupError !== null) return { findings: [], walk: { status: 'setup-failed', message: response.setupError } };\n if (response.errors.length > 0) return { findings: [], walk: { status: 'file-errors', errors: response.errors.map(error => svelte.error(error)) } };\n const snippetTrusted = decide(config.levels, level => level, 'svelte.__renderSnippet', 'svelte').trusted && !('distrustedBy' in decide(config.levels, level => level, 'svelte.Snippet', 'svelte'));\n const findings = response.findings.flatMap(finding => {\n const file = resolve(config.rootDir, finding.file);\n const mapped = svelte.finding(file, finding, snippetTrusted);\n return mapped ? [{ ...mapped, file: svelte.paths.has(file) ? relativeTo(config.rootDir, svelte.original(file)) : finding.file }] : [];\n });\n return { findings, walk: { status: 'ok' } };\n}\n","import { accessSync, constants, readFileSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport type NativeEngine = { readonly kind: 'binary'; readonly path: string } | { readonly kind: 'wasm'; readonly path: string };\ntype Libc = 'glibc' | 'musl' | null;\n\n/**\n * Native executables ship for Apple-silicon macOS, x64 GNU/Linux and x64 Windows, each built natively on a\n * self-hosted runner. Intel macOS, arm64 Linux, musl and every other platform use Wasm.\n */\nexport function nativePlatformPackage(platform: string, arch: string, libc: Libc = null): string | null {\n if (platform === 'darwin' && arch === 'arm64') return '@noego/trust-darwin-arm64';\n if (platform === 'linux' && libc === 'glibc' && arch === 'x64') return '@noego/trust-linux-x64-gnu';\n if (platform === 'win32' && arch === 'x64') return '@noego/trust-win32-x64-msvc';\n return null;\n}\n\n// The GNU release job builds on Ubuntu 24.04 (self-hosted). Older glibc must use Wasm, not a failing executable.\nexport const NATIVE_MINIMUM_GLIBC = '2.39';\n\nexport function supportsNativeGlibc(version: string | null): boolean {\n if (!version || !/^\\d+\\.\\d+(?:\\.\\d+)?$/.test(version)) return false;\n const [major, minor] = version.split('.').map(Number);\n const [minimumMajor, minimumMinor] = NATIVE_MINIMUM_GLIBC.split('.').map(Number);\n return major > minimumMajor || (major === minimumMajor && minor >= minimumMinor);\n}\n\nfunction runtimeLinux(platform: string): { libc: Libc; version: string | null } {\n if (platform !== 'linux') return { libc: null, version: null };\n try {\n const report = process.report?.getReport();\n if (typeof report !== 'object' || report === null) return { libc: null, version: null };\n const header = (report as { header?: { glibcVersionRuntime?: string } }).header;\n const version = header?.glibcVersionRuntime ?? null;\n return { libc: version ? 'glibc' : 'musl', version };\n } catch {\n // Unknown libc must not select a potentially incompatible GNU executable.\n return { libc: null, version: null };\n }\n}\n\n/** Optional inputs let discovery be tested without executing a compiler or mutating process globals. */\nexport interface EngineDiscovery {\n readonly roots?: readonly string[];\n readonly env?: NodeJS.ProcessEnv;\n readonly platform?: string;\n readonly arch?: string;\n readonly libc?: Libc;\n readonly glibcVersion?: string | null;\n readonly resolvePackage?: (specifier: string) => string;\n}\n\nconst requireFromHere = createRequire(import.meta.url);\n\nfunction packageRoots(): string[] {\n const here = dirname(fileURLToPath(import.meta.url));\n const roots = [resolve(here, '..', '..')];\n try {\n roots.unshift(dirname(requireFromHere.resolve('@noego/trust/package.json')));\n } catch {\n // A checkout run from src/ can use its relative root.\n }\n return [...new Set(roots)];\n}\n\nfunction isFile(path: string, executable = false, platform = process.platform as string): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n accessSync(path, executable && platform !== 'win32' ? constants.X_OK : constants.R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction packageVersion(roots: readonly string[], name: string): string | null {\n for (const root of roots) {\n try {\n const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; optionalDependencies?: Record<string, string> };\n const version = manifest.optionalDependencies?.[name];\n if (manifest.name === '@noego/trust' && typeof version === 'string' && /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) return version;\n } catch {\n // Try the next root.\n }\n }\n return null;\n}\n\n/** Explicit override, exact-version platform package, then a local development build. */\nexport function nativeBinary(options: EngineDiscovery = {}): string | null {\n const env = options.env ?? process.env;\n if (env.TRUST_NATIVE_BIN) return env.TRUST_NATIVE_BIN;\n const roots = options.roots ?? packageRoots();\n const platform = options.platform ?? process.platform;\n const linux = runtimeLinux(platform);\n const libc = options.libc === undefined ? linux.libc : options.libc;\n const glibcVersion = options.glibcVersion === undefined ? linux.version : options.glibcVersion;\n const supported = platform !== 'linux' || (libc === 'glibc' && supportsNativeGlibc(glibcVersion));\n const name = supported ? nativePlatformPackage(platform, options.arch ?? process.arch, libc) : null;\n const version = name ? packageVersion(roots, name) : null;\n const executable = platform === 'win32' ? 'trust-native.exe' : 'trust-native';\n if (name && version) {\n try {\n const manifestPath = (options.resolvePackage ?? requireFromHere.resolve)(`${name}/package.json`);\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { name?: string; version?: string };\n const candidate = join(dirname(manifestPath), 'bin', executable);\n // A stale or manually hoisted optional package must never run a different engine version.\n if (manifest.name === name && manifest.version === version && isFile(candidate, true, platform)) return candidate;\n } catch {\n // Optional dependencies may be omitted, unsupported, or unavailable. Wasm remains usable.\n }\n }\n return roots.map((root) => join(root, 'native', 'target', 'release', executable))\n .find((candidate) => isFile(candidate, true, platform)) ?? null;\n}\n\n/** Explicit override, packaged Wasm, then a local development build. */\nexport function nativeWasm(options: EngineDiscovery = {}): string | null {\n const env = options.env ?? process.env;\n if (env.TRUST_NATIVE_WASM) return env.TRUST_NATIVE_WASM;\n const candidates = (options.roots ?? packageRoots()).flatMap((root) => [\n join(root, 'dist', 'native', 'trust_native_wasm.wasm'),\n join(root, 'native', 'target', 'wasm32-wasip1', 'wasm', 'trust_native_wasm.wasm'),\n join(root, 'native', 'target', 'wasm32-wasip1', 'release', 'trust_native_wasm.wasm'),\n ]);\n return candidates.find((candidate) => isFile(candidate)) ?? null;\n}\n\n/** Native is preferred; the bundled Wasm works even with npm --omit=optional. */\nexport function nativeEngine(options: EngineDiscovery = {}): NativeEngine | null {\n const forced = (options.env ?? process.env).TRUST_NATIVE_ENGINE;\n if (forced !== 'wasm') {\n const path = nativeBinary(options);\n if (path) return { kind: 'binary', path };\n if (forced === 'binary') return null;\n }\n const path = nativeWasm(options);\n return path ? { kind: 'wasm', path } : null;\n}\n","// Native trust check. TypeScript is a build-time engine input, not a runtime dependency.\nimport { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { emptyTrustConfig } from '../core/check-file.js';\nimport { compareFindings, formatFinding } from '../core/report.js';\nimport { loadTrustConfig } from '../eslint/config.js';\nimport { groupMatches, realpathOrSelf, Zones } from '../eslint/zones.js';\nimport { checkNative } from './native-check.js';\nimport { formatWalkFailure, resolveFiles } from './source-files.js';\n\nexport interface CheckCommandOptions {\n readonly cwd: string;\n readonly paths: readonly string[];\n readonly configFile: string;\n readonly strict: boolean;\n readonly tsconfig?: string;\n readonly root?: string;\n readonly perf?: boolean;\n readonly json?: boolean;\n readonly log: (line: string) => void;\n}\n\n/** 0 clean/warnings only; 1 trust errors; 2 usage, configuration, syntax, or engine failure. */\nexport async function runCheckCommand(options: CheckCommandOptions): Promise<number> {\n const fail = (errors: readonly string[]): number => {\n if (options.json) options.log(JSON.stringify({ findings: [], errors, warnings: [] }));\n else for (const error of errors) options.log(error);\n return 2;\n };\n if (options.paths.length === 0) return fail(['trust check needs at least one path: trust check <paths...> [--strict] [--perf] [--json]']);\n try {\n const resolved = resolveFiles(options.cwd, options.paths);\n if ('missing' in resolved) return fail([`trust check: no such file or directory: ${resolved.missing}`]);\n const configPath = resolve(options.cwd, options.configFile);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = existsSync(configPath) ? loadTrustConfig(configPath, { rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);\n const warnings = config.unmatchedGlobs.map(line => `trust check: warning: ${line}`);\n const zones = new Zones(config.rootDir, config.passthrough, config.ignore);\n const files = resolved.files.filter(file => zones.zoneOf(file) !== 'ignore');\n const skipped = resolved.files.length - files.length;\n const strictByConfig = files.filter(file => config.strict.some(group => groupMatches(group, realpathOrSelf(file))));\n const result = await checkNative({\n cwd: options.cwd, files, config, programs: { tsconfig: options.tsconfig, mappings: config.tsconfig },\n strictFiles: options.strict ? files : strictByConfig, perf: options.perf,\n // Keep --json a single parseable document, even with debugging enabled.\n log: line => { if (!options.json) options.log(line); },\n });\n if (result.walk.status !== 'ok') return fail(formatWalkFailure('trust check', result.walk));\n const findings = result.findings.sort(compareFindings).map(finding => ({ ...finding, severity: finding.severity ?? 'error' }));\n const errors = findings.filter(finding => finding.severity === 'error').length;\n const advice = findings.length - errors;\n if (options.json) {\n options.log(JSON.stringify({ findings, errors: [], warnings, summary: { errors, warnings: advice, checkedFiles: files.length, skippedFiles: skipped } }));\n } else {\n for (const warning of warnings) options.log(warning);\n for (const finding of findings) options.log(formatFinding(finding));\n const notes: string[] = [];\n if (options.strict) notes.push('strict');\n else if (strictByConfig.length) notes.push(`${strictByConfig.length} strict by config`);\n if (options.perf) notes.push('perf');\n const counts = options.perf ? `${errors} error(s), ${advice} warning(s)` : `${findings.length} finding(s)`;\n options.log(`${counts} in ${files.length} checked file(s), ${skipped} ignored file(s) skipped${notes.length ? ` (${notes.join(', ')})` : ''}.`);\n }\n return errors > 0 ? 1 : 0;\n } catch (error) {\n return fail([`trust check: ${error instanceof Error ? error.message : String(error)}`]);\n }\n}\n","// One heavy Trust run per machine. `trust baseline`, `check` and `refactor` each hold a whole\n// TypeScript program (several GB on a large repo); agents in parallel worktrees used to start\n// many at once and push the machine into swap.\n//\n// Like sqlego's owner socket, the lock is a listening Unix socket (a named pipe on Windows), not\n// a pid file: the kernel closes it when the holder exits or is killed, so it cannot be left\n// stuck and pid reuse cannot fake a live holder. A run that finds it held stays connected and\n// wakes the moment the holder's socket closes. A socket file left by a crash refuses\n// connections and is removed; that removal is serialized through a short-lived `reclaim.lock`\n// whose age, not a pid, decides when it is stale.\n//\n// TRUST_RUNTIME_DIR moves the lock directory (default `<tmpdir>/noego-trust`).\n// TRUST_RUN_LOCK=0 skips the lock (e.g. a caller that already serializes runs).\nimport { closeSync, mkdirSync, openSync, rmSync, statSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { createConnection, createServer, type Server, type Socket } from 'node:net';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface RunLockOptions {\n readonly directory?: string;\n /** Called once, when the run first has to wait. */\n readonly onWait?: () => void;\n /** Age after which a leftover reclaim.lock is ignored (default 10 s). */\n readonly reclaimStaleMs?: number;\n}\n\nexport interface RunLock {\n readonly path: string;\n release(): Promise<void>;\n}\n\nexport function runLockDirectory(env: NodeJS.ProcessEnv = process.env): string {\n return env.TRUST_RUNTIME_DIR || join(tmpdir(), 'noego-trust');\n}\n\nexport function runLockDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.TRUST_RUN_LOCK === '0';\n}\n\nexport function runLockSocketPath(directory: string, platform: NodeJS.Platform = process.platform): string {\n if (platform !== 'win32') return join(directory, 'run.sock');\n const hash = createHash('sha256').update(directory).digest('hex').slice(0, 16);\n return `\\\\\\\\.\\\\pipe\\\\noego-trust-${hash}-run`;\n}\n\nfunction errnoCode(error: unknown): string | undefined {\n return (error as NodeJS.ErrnoException | undefined)?.code;\n}\n\ntype Listen = { readonly kind: 'held'; readonly server: Server } | { readonly kind: 'in-use' };\n\nfunction listen(socketPath: string): Promise<Listen> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n // EEXIST: on macOS, a bind racing another waiter's bind on the same path after a release.\n server.once('error', (error) => {\n const code = errnoCode(error);\n if (code === 'EADDRINUSE' || code === 'EEXIST') resolve({ kind: 'in-use' });\n else reject(error);\n });\n server.listen(socketPath, () => resolve({ kind: 'held', server }));\n });\n}\n\ntype Probe = { readonly kind: 'alive'; readonly socket: Socket } | { readonly kind: 'dead' };\n\nfunction probe(socketPath: string): Promise<Probe> {\n return new Promise((resolve, reject) => {\n const socket = createConnection(socketPath);\n socket.once('connect', () => resolve({ kind: 'alive', socket }));\n socket.once('error', (error) => {\n const code = errnoCode(error);\n // Refused: a crashed holder's socket file. ENOTSOCK: something else left at the path.\n if (code === 'ECONNREFUSED' || code === 'ENOENT' || code === 'ENOTSOCK') resolve({ kind: 'dead' });\n else reject(error);\n });\n });\n}\n\nfunction waitForClose(socket: Socket): Promise<void> {\n return new Promise((resolve) => {\n socket.once('close', () => resolve());\n socket.on('error', () => undefined); // ECONNRESET when the holder dies: 'close' follows.\n socket.on('data', () => undefined);\n });\n}\n\n/** Removes a dead holder's socket file, one reclaimer at a time; false when another is reclaiming. */\nfunction reclaim(directory: string, socketPath: string, staleMs: number): boolean {\n const guard = join(directory, 'reclaim.lock');\n try {\n closeSync(openSync(guard, 'wx'));\n } catch (error) {\n if (errnoCode(error) !== 'EEXIST') throw error;\n try {\n if (Date.now() - statSync(guard).mtimeMs < staleMs) return false;\n } catch {\n return false; // It vanished: the other reclaimer finished.\n }\n rmSync(guard, { force: true });\n return false;\n }\n try {\n rmSync(socketPath, { force: true });\n } finally {\n rmSync(guard, { force: true });\n }\n return true;\n}\n\n/** Waits until this process holds the machine-wide Trust run lock. */\nexport async function acquireRunLock(options: RunLockOptions = {}): Promise<RunLock> {\n const directory = options.directory ?? runLockDirectory();\n const reclaimStaleMs = options.reclaimStaleMs ?? 10_000;\n mkdirSync(directory, { recursive: true });\n const socketPath = runLockSocketPath(directory);\n let announced = false;\n for (;;) {\n const listened = await listen(socketPath);\n if (listened.kind === 'held') return holdLock(listened.server, socketPath);\n const probed = await probe(socketPath);\n if (probed.kind === 'dead') {\n if (!reclaim(directory, socketPath, reclaimStaleMs)) await new Promise((done) => setTimeout(done, 50));\n continue;\n }\n if (!announced) {\n announced = true;\n options.onWait?.();\n }\n await waitForClose(probed.socket);\n }\n}\n\nfunction holdLock(server: Server, socketPath: string): RunLock {\n const waiters = new Set<Socket>();\n server.on('connection', (socket) => {\n waiters.add(socket);\n socket.on('error', () => undefined);\n socket.once('close', () => waiters.delete(socket));\n });\n server.unref();\n let released: Promise<void> | undefined;\n const release = () => {\n released ??= new Promise<void>((resolve) => {\n // Closing the server removes the Unix socket file; destroying the connections wakes every waiter.\n server.close(() => resolve());\n for (const socket of waiters) socket.destroy();\n });\n return released;\n };\n return { path: socketPath, release };\n}\n","// `trust explain <file>:<line>[:<column>]` — which origin does each call on that line resolve to,\n// and why is it (un)trusted, both for failing (`trust`) and for its types (`trust_type`)? Tells the user\n// exactly which entry to add or remove. A call to a type guard or assertion function also says what it\n// narrows and whether the origin declaring it is type-trusted (`untrusted-value`'s `guard` entry). Also\n// lists every type claim that starts on the line (`type-claim`): its kind and why it is a claim; and every\n// untrusted value that starts on it (`untrusted-value`): how it entered, the origin that declared its type,\n// and whether its use is reported. Claims and values are listed only when the config turns their rule on,\n// as `trust check` reports them. A failure-path finding on the line that `//trust:accept <reason>` accepts\n// is listed with its reason. In a boundary file (`boundaries`), every boundary starting on the line is listed:\n// the item it belongs to, whether an `exclude` entry leaves it out, and what its return value says.\nimport { svelteFor, svelteForSource } from '../core/svelte.js';\nimport { resolve } from 'node:path';\nimport type * as TS from 'typescript';\nimport { boundaryContext, boundaryName, excludeMatches, fileBoundaries, itemLabel, type BoundaryVerdict } from '../core/boundaries.js';\nimport { checkSourceFileWithAccepted, isStrictByConfig, positionAt, startOf } from '../core/check-file.js';\nimport { ANY_KIND } from '../core/dropped-results.js';\nimport { BOUNDARY_RULE, formatFailureKinds, TYPE_CLAIM_RULE, UNTRUSTED_ENTRY_LABELS, UNTRUSTED_VALUE_RULE, type TypeClaimOrigin, type UntrustedEntry } from '../core/messages.js';\nimport { createPrograms, sourceFileOf, type MissingMappedTsconfig } from '../core/program.js';\nimport { claimSpan, typeClaimContext, typeClaimMessage, typeClaimsIn } from '../core/type-claims.js';\nimport {\n callTypeVerdict,\n guardCallOf,\n untrustedValueContext,\n untrustedValueMessage,\n untrustedValuesIn,\n type CallTypeVerdict,\n type GuardVerdict,\n type UntrustedOutcome,\n type UntrustedValueContext,\n} from '../core/untrusted-values.js';\nimport { isRuleEnabled, loadTrustConfig, type OptInRule } from '../eslint/config.js';\nimport { TrustPolicy, type Verdict } from '../eslint/policy.js';\nimport { loadTypeScript } from '../eslint/typescript.js';\n\nexport interface ExplainOptions {\n readonly cwd: string;\n readonly file: string;\n readonly line: number;\n readonly column?: number;\n readonly configFile: string;\n readonly tsconfig?: string;\n /** Directory the config's paths resolve against, instead of the config file's directory. */\n readonly root?: string;\n}\n\nexport interface ExplainedCall {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n /** Throw trust: may the call fail (`trust` / `distrust`)? */\n readonly verdict: Verdict;\n /** Type trust: is what the call returns what its type says (`trust_type` / `distrust_type`)? */\n readonly typeTrust: CallTypeVerdict;\n /** When the callee is a type guard or assertion function: what it narrows, and who vouches for that. */\n readonly guard: ExplainedGuard | null;\n readonly declaredAt: string | null;\n}\n\n/** A call to a type guard (`x is T`) or assertion function (`asserts x is T`): `untrusted-value`'s `guard` entry. */\nexport interface ExplainedGuard {\n /** The signature's predicate, as the call instantiates it (`data is User`). */\n readonly predicate: string;\n /** The value it narrows, as written at the call. */\n readonly narrows: string;\n readonly asserts: boolean;\n /** Type trust of the origin that declares the signature: `type-untrusted` makes the narrowed value untrusted. */\n readonly verdict: GuardVerdict;\n}\n\n/** One type claim starting at the location: what `trust check` reports there under `type-claim`. */\nexport interface ExplainedClaim {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n /** The claim kind (`claim:as`, `claim:non-null`, …), `unanalyzable`, or `directive` (a `//trust:` comment that marks nothing): the finding's origin and baseline key. */\n readonly origin: TypeClaimOrigin;\n /** Why it is a claim: the finding's message. */\n readonly why: string;\n}\n\n/** One untrusted value starting at the location: what `untrusted-value` decides there. */\nexport interface ExplainedValue {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n /** How the value entered checked code. */\n readonly entry: UntrustedEntry;\n /** The origin that declared its type: the finding's origin and baseline key, and the `trust_type` entry that would trust it. */\n readonly origin: string;\n /** The type it is declared to have. */\n readonly type: string;\n /** `finding` when `trust check` reports its use here. */\n readonly outcome: UntrustedOutcome;\n /** The finding's message, or why nothing is reported. */\n readonly why: string;\n}\n\n/** One failure-path finding starting at the location that a `//trust:accept` accepted: `trust check` does not report it. */\nexport interface ExplainedAcceptance {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n readonly rule: string;\n readonly origin: string;\n /** The finding's message: what would be reported without the directive. */\n readonly why: string;\n /** The reason written after `//trust:accept`. */\n readonly reason: string;\n /** 1-based line of the directive. */\n readonly directiveLine: number;\n}\n\n/** One boundary (exported function or public member of a boundary file) starting at the location. */\nexport interface ExplainedBoundary {\n readonly line: number;\n readonly column: number;\n /** `Class.member` or `fn`: the name an `exclude` entry uses. */\n readonly member: string;\n /** The `boundaries` item the file belongs to (`boundaries[0] in trust.config.json`). */\n readonly item: string;\n /** The `exclude` entry that leaves it out, or null. */\n readonly excludedBy: string | null;\n /** What its return value says: plain data, a Result that can fail, or `any` / `unknown`. */\n readonly verdict: BoundaryVerdict;\n /** Whether `trust check` reports it (not excluded, and not plain data), and as what. */\n readonly reported: 'error' | 'warning' | null;\n}\n\nexport interface Explanation {\n readonly file: string;\n readonly zone: string;\n readonly calls: readonly ExplainedCall[];\n readonly claims: readonly ExplainedClaim[];\n readonly values: readonly ExplainedValue[];\n readonly accepted: readonly ExplainedAcceptance[];\n readonly boundaries: readonly ExplainedBoundary[];\n /** Opt-in rules the config leaves off: their claims / values are not listed (nor reported by `trust check`). */\n readonly off: readonly OptInRule[];\n}\n\nfunction clipText(raw: string): string {\n const text = raw.replace(/\\s+/g, ' ');\n return text.length > 80 ? `${text.slice(0, 77)}...` : text;\n}\n\nfunction declaredAt(ts: typeof TS, policy: TrustPolicy, node: TS.CallExpression | TS.NewExpression): string | null {\n const resolved = policy.calleeDeclaration(node);\n if (!resolved) return null;\n const source = resolved.declaration.getSourceFile();\n const { line } = ts.getLineAndCharacterOfPosition(source, resolved.declaration.getStart(source));\n const inputs = svelteForSource(source);\n const original = inputs?.position(source.fileName, startOf(ts, source, resolved.declaration));\n return `${inputs?.original(source.fileName) ?? source.fileName}:${original?.line ?? line + 1}`;\n}\n\nfunction explainGuard(call: TS.CallExpression, source: TS.SourceFile, context: UntrustedValueContext): ExplainedGuard | null {\n const guard = guardCallOf(call, context);\n return guard ? { predicate: guard.predicate, narrows: clipText(guard.argument.getText(source)), asserts: guard.asserts, verdict: guard.verdict } : null;\n}\n\nconst NOT_REPORTED: Readonly<Record<Exclude<UntrustedOutcome, 'finding'>, string>> = {\n allowed: 'not reported: it is passed to a validator, kept as `unknown`, tested by a built-in check, or kept in a variable with no written type',\n 'no-claim': 'not reported: its type claims nothing (`unknown`, `any`, an empty type or a function)',\n validator: 'not reported: it is inside a validator',\n};\n\nexport type ExplainResult = { readonly kind: 'explained'; readonly explanation: Explanation } | MissingMappedTsconfig;\n\n/** The file compiles under `--tsconfig`, else the config's matching `tsconfig` entry, else the nearest tsconfig.json. */\nexport function explain(options: ExplainOptions): ExplainResult {\n const ts = loadTypeScript(options.cwd);\n const file = resolve(options.cwd, options.file);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = loadTrustConfig(resolve(options.cwd, options.configFile), { rootDir });\n const creation = createPrograms(ts, options.cwd, [file], options.tsconfig, config.tsconfig);\n if (creation.kind !== 'created') return creation;\n const [{ program }] = creation.groups;\n const source = sourceFileOf(program, file);\n if (!source) throw new Error(`could not load ${file} into a TypeScript program`);\n const checker = program.getTypeChecker();\n const policy = new TrustPolicy(ts, checker, config);\n const valueContext = untrustedValueContext(ts, checker, policy);\n const generatedLines = svelteFor(checker)?.generatedLines(source.fileName, options.line);\n const here = (position: { line: number; column: number }): { line: number; column: number } | null => {\n if (generatedLines && !generatedLines.has(position.line)) return null;\n const mapped = svelteFor(checker)?.position(source.fileName, position);\n if (mapped === null) return null;\n position = mapped ?? position;\n const onLine = position.line === options.line;\n return onLine && (options.column === undefined || position.column === options.column) ? position : null;\n };\n const calls: ExplainedCall[] = [];\n const visit = (node: TS.Node): void => {\n if (ts.isCallExpression(node) || ts.isNewExpression(node)) {\n const position = here(startOf(ts, source, node));\n if (position) {\n calls.push({\n ...position,\n text: clipText(node.getText(source)),\n verdict: (() => {\n const verdict = policy.classify(node);\n const wrapper = policy.lookup('svelte.__renderSnippet', 'svelte');\n return verdict.kind === 'untrusted' && !verdict.distrustedBy && verdict.origin.origin === 'svelte.Snippet'\n && svelteFor(checker)?.snippetCall(source.fileName, node.getStart(source)) && wrapper.trusted\n ? { kind: 'trusted' as const, origin: verdict.origin, by: wrapper.by } : verdict;\n })(),\n typeTrust: callTypeVerdict(node, valueContext),\n guard: ts.isCallExpression(node) ? explainGuard(node, source, valueContext) : null,\n declaredAt: declaredAt(ts, policy, node),\n });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n // The same decisions `trust check` reports under `type-claim`, with the finding's message as the reason\n // (a directive finding is reported at its comment, so its text is the comment).\n const claimsOn = isRuleEnabled(config, TYPE_CLAIM_RULE);\n const valuesOn = isRuleEnabled(config, UNTRUSTED_VALUE_RULE);\n // Only the rules explain lists items for; dropped-result findings are explained by their message.\n const explained: readonly OptInRule[] = [TYPE_CLAIM_RULE, UNTRUSTED_VALUE_RULE];\n const off = explained.filter((rule) => !isRuleEnabled(config, rule));\n const claims = (claimsOn ? typeClaimsIn(source, typeClaimContext(ts, checker, undefined, policy)) : []).flatMap((claim): ExplainedClaim[] => {\n const span = claimSpan(claim, source);\n const position = here(positionAt(ts, source, span.start));\n return position ? [{ ...position, text: clipText(source.text.slice(span.start, span.end)), origin: claim.origin, why: typeClaimMessage(claim) }] : [];\n });\n // The same decisions `trust check` reports under `untrusted-value`, and the untrusted values it lets pass.\n // Left out, because another block already explains them: a value a member is read from when that member\n // is itself an untrusted value (`process.env` in `process.env.HOME`: the member read is the one explained),\n // and a call whose result claims nothing (`void`, `unknown`, `any`: its call block has the type-trust verdict).\n const found = valuesOn ? untrustedValuesIn(source, valueContext) : [];\n const valueNodes = new Set<TS.Node>(found.map((value) => value.node));\n const isReadThrough = (node: TS.Node): boolean =>\n (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node && valueNodes.has(node.parent);\n const isCall = (node: TS.Node): boolean => ts.isCallExpression(node) || ts.isNewExpression(node);\n const values = found.flatMap((value): ExplainedValue[] => {\n const position = here(startOf(ts, source, value.node));\n if (!position || isReadThrough(value.node) || (value.outcome === 'no-claim' && isCall(value.node))) return [];\n const why = value.outcome === 'finding' ? untrustedValueMessage(value) : NOT_REPORTED[value.outcome];\n return [{ ...position, text: clipText(value.node.getText(source)), entry: value.entry, origin: value.origin, type: value.type, outcome: value.outcome, why }];\n });\n // The failure-path findings `trust check` would report here but a `//trust:accept` accepts, with its reason.\n const accepted = checkSourceFileWithAccepted({ ts, program, checker, config, sourceFile: source }).accepted.flatMap((entry): ExplainedAcceptance[] => {\n const { finding, acceptance } = entry;\n const position = here({ line: finding.line, column: finding.column });\n if (!position) return [];\n const directivePosition = positionAt(ts, source, acceptance.directive.pos);\n const directiveLine = svelteFor(checker)?.position(source.fileName, directivePosition)?.line ?? directivePosition.line;\n return [{ ...position, text: clipText(entry.text), rule: finding.rule, origin: finding.origin, why: finding.message, reason: acceptance.reason, directiveLine }];\n });\n // The boundaries of a boundary file (`boundaries` in the config) that start on the line, as boundary-result sees them.\n const boundaries: ExplainedBoundary[] = [];\n if (config.boundaries.length > 0) {\n const found = fileBoundaries(source, boundaryContext(ts, checker, program, policy, config));\n if (found.kind === 'boundary') {\n const strict = isStrictByConfig(config, source.fileName);\n for (const boundary of found.boundaries) {\n const position = here(positionAt(ts, source, boundary.start));\n if (!position) continue;\n const excludedBy = found.item.exclude.find((entry) => excludeMatches(entry, boundary)) ?? null;\n const reported = excludedBy || boundary.verdict.kind === 'plain' ? null : boundary.verdict.kind === 'result' || strict ? 'error' : 'warning';\n boundaries.push({ ...position, member: boundaryName(boundary), item: itemLabel(found.item), excludedBy, verdict: boundary.verdict, reported });\n }\n }\n }\n const unique = <T>(items: T[]): T[] => [...new Map(items.map(item => [JSON.stringify(item), item])).values()];\n return {\n kind: 'explained',\n explanation: { file, zone: policy.zones.zoneOf(file), calls: unique(calls), claims: unique(claims), values: unique(values), accepted: unique(accepted), boundaries: unique(boundaries), off },\n };\n}\n\n/** The lines of one boundary: the item, the exclusion, and what the return value says. */\nfunction describeBoundary(boundary: ExplainedBoundary): string[] {\n const lines = [` boundary: ${boundary.member} (${boundary.item}, rule ${BOUNDARY_RULE})`];\n const { verdict } = boundary;\n const returns =\n verdict.kind === 'plain'\n ? 'plain data: nothing reported'\n : verdict.kind === 'result'\n ? verdict.kinds.length === 0\n ? 'a Result object that cannot fail'\n : `a Result that can fail with ${formatFailureKinds(verdict.kinds, ANY_KIND)}`\n : `\\`${verdict.type}\\`, which may hold a Result`;\n if (boundary.excludedBy) lines.push(` returns: ${returns}`, ` excluded: by \"${boundary.excludedBy}\" in the item's \"exclude\": nothing reported`);\n else if (boundary.reported) lines.push(` returns: ${returns}: reported as ${boundary.reported === 'warning' ? 'a warning (an error where strict applies)' : 'an error'}`);\n else lines.push(` returns: ${returns}`);\n return lines;\n}\n\nfunction describe(verdict: Verdict): string[] {\n switch (verdict.kind) {\n case 'unresolved':\n return ['verdict: not checked (callee has no declaration, e.g. an `any` value)'];\n case 'first-party':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (first-party code in a checked file is checked itself)'];\n case 'returns-result':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (declared return type is Result from @noego/trust)'];\n case 'trusted':\n return [`origin: ${verdict.origin.origin}`, `verdict: trusted by \"${verdict.by.entry}\" in ${verdict.by.source}`];\n case 'calls-ignored':\n return [\n `origin: ${verdict.origin.origin}`,\n 'verdict: reported (callsIgnored): the callee file is ignored; make it passthrough so calls into it must be handled',\n ];\n case 'untrusted':\n return [\n `origin: ${verdict.origin.origin}`,\n verdict.distrustedBy\n ? `verdict: UNTRUSTED (distrusted by \"${verdict.distrustedBy.entry}\" in ${verdict.distrustedBy.source})`\n : 'verdict: UNTRUSTED (no trust entry matches)',\n `hint: guard it, or trust \"${verdict.origin.origin}\" (or a prefix of it) in trust.config.json`,\n ];\n }\n}\n\n/** The type-trust lines of a call: is what it returns what its type says? */\nfunction describeTypeTrust(verdict: CallTypeVerdict): string[] {\n switch (verdict.kind) {\n case 'unresolved':\n return [];\n case 'first-party':\n return ['types: trusted (first-party code in a checked file is checked itself)'];\n case 'trust-package':\n return ['types: trusted (declared by @noego/trust)'];\n case 'validator':\n return ['types: trusted (the callee is a validator: //trust:validator_function)'];\n case 'type-trusted':\n return [`types: type-trusted by \"${verdict.by.entry}\" in ${verdict.by.source}`];\n case 'caller-chosen-generic':\n return [\n 'types: UNTRUSTED (the call picks its own return type: a type parameter found only in the return position, which no type trust proves)',\n ' validate the returned value',\n ];\n case 'type-untrusted':\n return [\n verdict.distrustedBy\n ? `types: UNTRUSTED (type-distrusted by \"${verdict.distrustedBy.entry}\" in ${verdict.distrustedBy.source})`\n : 'types: UNTRUSTED (no trust_type entry matches)',\n ` validate what it returns, or add \"${verdict.origin.origin}\" (or a prefix of it) to \"trust_type\" in trust.config.json`,\n ];\n }\n}\n\n/** The guard lines of a call to a type guard or assertion function: is what it narrows what its predicate says? */\nfunction describeGuard(guard: ExplainedGuard): string[] {\n const head = `guard: ${guard.asserts ? 'asserts' : 'narrows'} \"${guard.narrows}\" (${guard.predicate}), declared by \"${guard.verdict.origin.origin}\"`;\n switch (guard.verdict.kind) {\n case 'first-party':\n return [head, ' not an untrusted value: first-party code in a checked file (its written predicate is a type claim, rule type-claim)'];\n case 'trust-package':\n return [head, ' trusted (declared by @noego/trust)'];\n case 'validator':\n return [head, ' trusted (the guard is a validator: //trust:validator_function)'];\n case 'built-in':\n return [head, ' trusted (a built-in check)'];\n case 'type-trusted':\n return [head, ` type-trusted by \"${guard.verdict.by.entry}\" in ${guard.verdict.by.source}`];\n case 'type-untrusted':\n return [\n head,\n guard.verdict.distrustedBy\n ? ` UNTRUSTED (type-distrusted by \"${guard.verdict.distrustedBy.entry}\" in ${guard.verdict.distrustedBy.source}): the narrowed value is untrusted (rule ${UNTRUSTED_VALUE_RULE})`\n : ` UNTRUSTED (no trust_type entry matches): the narrowed value is untrusted (rule ${UNTRUSTED_VALUE_RULE})`,\n ` validate the value instead, or add \"${guard.verdict.origin.origin}\" (or a prefix of it) to \"trust_type\" in trust.config.json`,\n ];\n }\n}\n\nexport function formatExplanation(explanation: Explanation): string {\n const lines = [`${explanation.file} (zone: ${explanation.zone})`];\n if (explanation.zone !== 'checked') {\n lines.push('note: calls, type claims and untrusted values in this file are not checked (only checked-zone files are linted)');\n }\n for (const rule of explanation.off) {\n lines.push(`note: ${rule} is off in this config, so it is not explained; turn it on with \"rules\": { \"${rule}\": \"on\" } in trust.config.json`);\n }\n if (explanation.calls.length === 0 && explanation.claims.length === 0 && explanation.values.length === 0 && explanation.accepted.length === 0 && explanation.boundaries.length === 0) {\n lines.push('no call, `new` expression, type claim, untrusted value or boundary starts at that location');\n }\n for (const boundary of explanation.boundaries) {\n lines.push('', `${boundary.line}:${boundary.column} ${boundary.member}`);\n lines.push(...describeBoundary(boundary));\n }\n for (const accepted of explanation.accepted) {\n lines.push('', `${accepted.line}:${accepted.column} ${accepted.text}`);\n lines.push(` accepted: ${accepted.rule} (${accepted.origin}) by //trust:accept on line ${accepted.directiveLine}`);\n lines.push(` reason: ${accepted.reason}`);\n lines.push(` finding: ${accepted.why}`);\n }\n for (const call of explanation.calls) {\n lines.push('', `${call.line}:${call.column} ${call.text}`);\n for (const detail of describe(call.verdict)) lines.push(` ${detail}`);\n for (const detail of describeTypeTrust(call.typeTrust)) lines.push(` ${detail}`);\n if (call.guard) for (const detail of describeGuard(call.guard)) lines.push(` ${detail}`);\n if (call.declaredAt) lines.push(` declared: ${call.declaredAt}`);\n }\n for (const claim of explanation.claims) {\n lines.push('', `${claim.line}:${claim.column} ${claim.text}`);\n lines.push(` claim: ${claim.origin} (rule ${TYPE_CLAIM_RULE})`);\n lines.push(` why: ${claim.why}`);\n }\n for (const value of explanation.values) {\n lines.push('', `${value.line}:${value.column} ${value.text}`);\n lines.push(` value: untrusted \"${value.type}\", ${UNTRUSTED_ENTRY_LABELS[value.entry]} \"${value.origin}\" (rule ${UNTRUSTED_VALUE_RULE})`);\n lines.push(` use: ${value.why}`);\n }\n return lines.join('\\n');\n}\n","// `trust refactor [paths…] [--baseline <path>] [--json] [--value-only] [--max-group <n>] [--tsconfig <path>] [--root <dir>]`\n// — the order to refactor a tree in. A file's inferred failure and return types change when the files\n// it imports change, so the work starts at the leaves. The command builds the static import graph of\n// the files `trust baseline` would check (same file walk, programs, tsconfig mapping and ignore zone),\n// collapses circular imports into groups, layers the result into waves, and keeps only the files that\n// have findings: the ones in trust-baseline.json, or those of a fresh check when there is no baseline.\n//\n// A circular group above the size threshold is too large for one unit of work. It is shrunk in steps,\n// and nothing above the threshold leaves without saying so:\n// 1. the imports inside it that cannot carry a change (an interface, a constant, a frozen Result\n// contract: core/change.ts) are left out, and what is left is planned again;\n// 2. a group still too large gets an internal order: its declarations with findings, callees first,\n// from the calls between its declarations (core/call-graph.ts);\n// 3. declarations that call each other in a circle are reported with the calls that close the circle\n// and the two ways out (freeze a contract, or iterate to a fixed point).\n// Every circular group, of any size, lists the imports that close it (optional structural cleanup).\n// Runs on TypeScript alone (no ESLint).\nimport { svelteFor } from '../core/svelte.js';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type * as TS from 'typescript';\nimport { collectCalls, declarationAt } from '../core/call-graph.js';\nimport { changeOracleFor } from '../core/change.js';\nimport { checkSourceFile, emptyTrustConfig, policyFor } from '../core/check-file.js';\nimport { collectImports } from '../core/import-graph.js';\nimport { planRefactor, type CircularGroup, type PlanEdge, type WorkItem } from '../core/refactor-plan.js';\nimport { loadTrustConfig, type TrustConfig } from '../eslint/config.js';\nimport type { TypeScript } from '../eslint/typescript.js';\nimport { realpathOrSelf, Zones } from '../eslint/zones.js';\nimport { readBaseline } from './baseline-command.js';\nimport { forEachSourceFile, logUnmatchedGlobs, logWalkFailure, relativeTo, resolveFiles } from './source-files.js';\n\n/** A circular group with more files than this is reported as too large for one unit of work. */\nexport const DEFAULT_MAX_GROUP_SIZE = 8;\n\n/** Cutting an import costs this much per imported name that can change, and 1 per name that cannot. */\nconst CHANGING_NAME_COST = 10;\n\nexport interface RefactorCommandOptions {\n readonly cwd: string;\n /** Files or directories; the current directory when empty. */\n readonly paths: readonly string[];\n readonly configFile: string;\n /** Where the tasks come from; `<root>/trust-baseline.json` when omitted, a fresh check when that does not exist. */\n readonly baselineFile?: string;\n /** Print the plan as JSON instead of text. */\n readonly json: boolean;\n /** Leave type-only imports out of the graph. */\n readonly valueOnly: boolean;\n /** Defaults to DEFAULT_MAX_GROUP_SIZE. */\n readonly maxGroupSize?: number;\n /** One tsconfig for every file, instead of the config's `tsconfig` entries or the nearest tsconfig.json. */\n readonly tsconfig?: string;\n /** Directory the config's paths resolve against, instead of the config file's directory. */\n readonly root?: string;\n readonly log: (line: string) => void;\n}\n\n/** An `import(...)` whose specifier is computed: the graph has no edge for it. */\nexport interface ComputedImportWarning {\n readonly kind: 'computed-import';\n readonly file: string;\n readonly line: number;\n readonly column: number;\n readonly specifier: string;\n}\n\n/** An import that closes a circular group: `from` imports `names` from `to` (`*` is the module as a whole). */\nexport interface ClosingImport {\n readonly from: string;\n readonly to: string;\n readonly names: readonly string[];\n}\n\n/** A call that closes a recursion: the declaration `from` calls the declaration `to` at `callSites` places. */\nexport interface ClosingCall {\n readonly from: string;\n readonly to: string;\n readonly callSites: number;\n}\n\n/** Declarations that call each other in a circle: no order between them. */\nexport interface RecursionGroup {\n readonly size: number;\n /** `file#declaration`, sorted. */\n readonly declarations: readonly string[];\n /** The declarations among them that have findings. */\n readonly tasks: readonly string[];\n /** The files they are declared in, sorted. */\n readonly files: readonly string[];\n /** Calls that close the circle: without them it has an order. */\n readonly closingEdges: readonly ClosingCall[];\n /**\n * The cut to make when freezing a contract: the callee of a closing call with the fewest call sites in\n * the group's files. Writing its return type as a Result by hand stops changes from travelling through it.\n */\n readonly freeze: { readonly declaration: string; readonly callSites: number };\n}\n\n/** A circular group that is left of a too-large one once the imports that cannot carry a change are gone. */\nexport interface RemainingGroup {\n readonly size: number;\n readonly files: readonly string[];\n readonly tasks: readonly string[];\n /** Still more files than the threshold: it stays one work item and has an internal `order`. */\n readonly tooLarge: boolean;\n /** Imports that carry a change and close the group. */\n readonly closingEdges: readonly ClosingImport[];\n /**\n * Only when `tooLarge`: its declarations with findings (`file#declaration`) in waves, callees first.\n * A string is one declaration, an array is a recursion to change together.\n */\n readonly order?: WorkItem[][];\n /** Only when `tooLarge`: the recursions among its declarations, largest first. */\n readonly recursion?: readonly RecursionGroup[];\n}\n\nexport interface ReportedGroup {\n readonly size: number;\n readonly files: readonly string[];\n readonly tasks: readonly string[];\n readonly tooLarge: boolean;\n /** Imports that close the group: removing them is optional structural cleanup that ends the circle. */\n readonly closingEdges: readonly ClosingImport[];\n /** Only when `tooLarge`: what is left of the group without the imports that cannot carry a change. */\n readonly split?: {\n readonly droppedEdges: number;\n readonly keptEdges: number;\n readonly groups: readonly RemainingGroup[];\n };\n}\n\n/** What `trust refactor --json` prints. */\nexport interface RefactorReport {\n /** Waves in order; a string is one file, an array is a circular group to refactor together. */\n readonly waves: WorkItem[][];\n /** Every circular group of the import graph, largest first. */\n readonly cycles: readonly ReportedGroup[];\n readonly warnings: readonly ComputedImportWarning[];\n readonly summary: {\n /** Files in the graph. */\n readonly files: number;\n /** Import edges between them. */\n readonly edges: number;\n /** Files with findings. */\n readonly tasks: number;\n /** Work items (files and groups) over all waves. */\n readonly items: number;\n readonly ignored: number;\n /** `baseline`: tasks are the baseline's files; `check`: tasks are the files a fresh check found findings in. */\n readonly taskSource: 'baseline' | 'check';\n readonly baseline: string | null;\n readonly valueOnly: boolean;\n readonly maxGroupSize: number;\n };\n}\n\nfunction hasFindings(byRule: Record<string, Record<string, number>>): boolean {\n return Object.values(byRule).some((byOrigin) => Object.values(byOrigin).some((count) => count > 0));\n}\n\nfunction byName(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** One file of the walk, kept to read its calls when its group needs an internal order. */\ninterface Loaded {\n readonly ts: TypeScript;\n readonly program: TS.Program;\n readonly sourceFile: TS.SourceFile;\n}\n\ninterface InternalOrder {\n readonly order: WorkItem[][];\n readonly recursion: RecursionGroup[];\n}\n\n/**\n * The order inside one circular group, from the calls between its declarations. A declaration is\n * work when a fresh check has a finding in it and its file is a task; the others only carry the order.\n */\nfunction internalOrder(\n group: CircularGroup,\n loaded: ReadonlyMap<string, Loaded>,\n config: TrustConfig,\n keyOfTarget: (target: string) => string | undefined,\n maxGroupSize: number,\n): InternalOrder {\n const inGroup = new Set(group.files);\n const taskFiles = new Set(group.tasks);\n /** caller → callee → call sites, as `file#declaration`. */\n const calls = new Map<string, Map<string, number>>();\n const declarations = new Set<string>();\n const withFindings = new Set<string>();\n for (const file of group.files) {\n const entry = loaded.get(file);\n if (!entry) continue;\n const { ts, program, sourceFile } = entry;\n const checker = program.getTypeChecker();\n const policy = policyFor(ts, checker, config);\n for (const call of collectCalls(ts, policy, changeOracleFor(ts, checker, policy), sourceFile)) {\n const targetFile = keyOfTarget(policy.zones.virtualPaths.get(call.targetFile) ?? call.targetFile);\n if (targetFile === undefined || !inGroup.has(targetFile)) continue;\n const from = `${file}#${call.from}`;\n const to = `${targetFile}#${call.to}`;\n if (from === to) continue;\n declarations.add(from).add(to);\n let callees = calls.get(from);\n if (!callees) {\n callees = new Map();\n calls.set(from, callees);\n }\n callees.set(to, (callees.get(to) ?? 0) + 1);\n }\n if (!taskFiles.has(file)) continue;\n for (const finding of checkSourceFile({ ts, program, config, sourceFile })) {\n const declaration = `${file}#${declarationAt(ts, sourceFile, finding.line, finding.column)}`;\n declarations.add(declaration);\n withFindings.add(declaration);\n }\n }\n\n const callSites = (from: string, to: string): number => calls.get(from)?.get(to) ?? 0;\n const incoming = new Map<string, number>();\n for (const callees of calls.values()) {\n for (const [callee, count] of callees) incoming.set(callee, (incoming.get(callee) ?? 0) + count);\n }\n const plan = planRefactor({\n files: [...declarations],\n dependencies: new Map([...calls].map(([from, callees]) => [from, [...callees.keys()]])),\n tasks: withFindings,\n maxGroupSize,\n weight: callSites,\n });\n const recursion = plan.cycles.map((cycle): RecursionGroup => {\n const cuts = [...new Set(cycle.closingEdges.map((edge) => edge.to))]\n .map((declaration) => ({ declaration, callSites: incoming.get(declaration) ?? 0 }))\n .sort((a, b) => a.callSites - b.callSites || byName(a.declaration, b.declaration));\n return {\n size: cycle.size,\n declarations: cycle.files,\n tasks: cycle.tasks,\n files: [...new Set(cycle.files.map((declaration) => declaration.slice(0, declaration.indexOf('#'))))].sort(),\n closingEdges: cycle.closingEdges.map((edge) => ({ ...edge, callSites: callSites(edge.from, edge.to) })),\n freeze: cuts[0],\n };\n });\n return { order: plan.waves, recursion };\n}\n\nfunction formatItem(item: WorkItem, tooLarge: boolean): string[] {\n if (typeof item === 'string') return [` ${item}`];\n const how = tooLarge ? 'circular imports, too large for one unit: follow its internal order below' : 'circular imports, refactor together';\n return [` group of ${item.length} (${how}):`, ...item.map((file) => ` ${file}`)];\n}\n\nfunction formatClosingImport(edge: ClosingImport): string {\n return `closed by: ${edge.from} imports ${edge.names.join(', ')} from ${edge.to}`;\n}\n\nfunction formatDeclarations(item: WorkItem): string {\n return typeof item === 'string' ? item : `(${item.join(' + ')})`;\n}\n\nfunction formatRecursion(group: RecursionGroup, indent: string): string[] {\n return [\n `${indent}${group.declarations.join(', ')}`,\n ...group.closingEdges.map((edge) => `${indent} closed by: ${edge.from} calls ${edge.to} (${edge.callSites} call site(s))`),\n `${indent} freeze a contract: write the return type of ${group.freeze.declaration} as a Result by hand (${group.freeze.callSites} call site(s) in the group); changes stop there`,\n `${indent} or iterate to a fixed point: refactor these declarations in passes until their inferred failure types stop growing (they only grow, so it ends)`,\n ];\n}\n\nfunction formatRemaining(group: RemainingGroup, maxGroupSize: number, indent: string): string[] {\n const tooLarge = group.tooLarge ? ` — still too large for one unit (more than ${maxGroupSize} files)` : '';\n const lines = [`${indent}${group.size} file(s), ${group.tasks.length} with findings${tooLarge}: ${group.files.join(', ')}`];\n for (const edge of group.closingEdges) lines.push(`${indent} ${formatClosingImport(edge)}`);\n const { order, recursion } = group;\n if (order) {\n const count = order.reduce((sum, wave) => sum + wave.reduce((inWave, item) => inWave + (typeof item === 'string' ? 1 : item.length), 0), 0);\n lines.push(count === 0 ? `${indent} internal order: no declaration with findings` : `${indent} internal order of the ${count} declaration(s) with findings, callees first:`);\n order.forEach((wave, index) => lines.push(`${indent} ${index + 1}. ${wave.map(formatDeclarations).join(', ')}`));\n }\n if (recursion && recursion.length > 0) {\n lines.push(`${indent} mutual recursion (${recursion.length}): declarations that call each other in a circle, with two ways out`);\n for (const circle of recursion) lines.push(...formatRecursion(circle, `${indent} `));\n }\n return lines;\n}\n\nfunction formatCycle(cycle: ReportedGroup, maxGroupSize: number): string[] {\n const tooLarge = cycle.tooLarge ? ` — too large for one unit (more than ${maxGroupSize} files)` : '';\n const lines = [` ${cycle.size} file(s), ${cycle.tasks.length} with findings${tooLarge}: ${cycle.files.join(', ')}`];\n for (const edge of cycle.closingEdges) lines.push(` ${formatClosingImport(edge)}`);\n const split = cycle.split;\n if (!split) return lines;\n const left = split.groups.length === 0 ? 'no circular group left' : `${split.groups.length} circular group(s) left`;\n lines.push(` without the ${split.droppedEdges} import(s) that cannot carry a change (${split.keptEdges} kept): ${left}`);\n for (const group of split.groups) lines.push(...formatRemaining(group, maxGroupSize, ' '));\n return lines;\n}\n\nfunction formatReport(report: RefactorReport): string[] {\n const { waves, cycles, warnings, summary } = report;\n // The groups of the plan that are still above the threshold, by their first task (the first file of their work item).\n const tooLarge = new Set<string>();\n for (const cycle of cycles) {\n for (const group of cycle.split ? cycle.split.groups : [cycle]) {\n if (group.tooLarge && group.tasks.length > 1) tooLarge.add(group.tasks[0]);\n }\n }\n const lines: string[] = [];\n waves.forEach((wave, index) => {\n lines.push(`Wave ${index + 1} of ${waves.length} (${wave.length} item(s)):`);\n for (const item of wave) lines.push(...formatItem(item, typeof item !== 'string' && tooLarge.has(item[0])));\n });\n if (waves.length === 0) lines.push('No file with findings: nothing to refactor.');\n if (cycles.length > 0) {\n lines.push(`Circular import groups (${cycles.length}):`);\n for (const cycle of cycles) lines.push(...formatCycle(cycle, summary.maxGroupSize));\n }\n if (warnings.length > 0) {\n lines.push(`Computed import() the graph cannot follow (${warnings.length}):`);\n for (const warning of warnings) lines.push(` ${warning.file}:${warning.line}:${warning.column} import(${warning.specifier})`);\n }\n const source = summary.taskSource === 'baseline' ? `the baseline ${summary.baseline}` : 'a fresh check (no baseline file)';\n const imports = summary.valueOnly ? 'value import(s)' : 'import(s)';\n lines.push(\n `${summary.tasks} file(s) with findings in ${summary.items} work item(s) over ${waves.length} wave(s); ` +\n `${summary.files} file(s) and ${summary.edges} ${imports} in the graph, ${summary.ignored} ignored file(s) skipped; findings from ${source}.`,\n );\n return lines;\n}\n\n/** Returns the process exit code: 0 plan printed, 2 could not run (TypeScript, an unloadable file, an unreadable or missing baseline). */\nexport async function runRefactorCommand(options: RefactorCommandOptions): Promise<number> {\n const maxGroupSize = options.maxGroupSize ?? DEFAULT_MAX_GROUP_SIZE;\n if (!Number.isInteger(maxGroupSize) || maxGroupSize < 1) {\n options.log('trust refactor: --max-group needs a whole number of files, 1 or more');\n return 2;\n }\n const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ['.']);\n if ('missing' in resolved) {\n options.log(`trust refactor: no such file or directory: ${resolved.missing}`);\n return 2;\n }\n const configPath = resolve(options.cwd, options.configFile);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = existsSync(configPath)\n ? loadTrustConfig(configPath, { rootDir })\n : emptyTrustConfig(rootDir ?? options.cwd);\n logUnmatchedGlobs(options.log, 'refactor', config);\n const zones = new Zones(config.rootDir, config.passthrough, config.ignore);\n const files = resolved.files.filter((file) => zones.zoneOf(file) !== 'ignore');\n\n // The baseline names the tasks when there is one. A baseline named on the command line must exist.\n const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, 'trust-baseline.json'));\n const fromBaseline = existsSync(baselineFile);\n if (!fromBaseline && options.baselineFile !== undefined) {\n options.log(`trust refactor: no such baseline: ${options.baselineFile}`);\n return 2;\n }\n const baseline = readBaseline(baselineFile);\n if ('error' in baseline) {\n options.log(`trust refactor: could not read the baseline: ${baseline.error}`);\n return 2;\n }\n\n // Graph nodes are baseline keys. Programs name files their own way, so targets are matched by path, then by realpath.\n const keyByPath = new Map<string, string>();\n for (const file of files) {\n const key = relativeTo(config.rootDir, file);\n keyByPath.set(file, key);\n keyByPath.set(realpathOrSelf(file), key);\n }\n const keyOfTarget = (target: string): string | undefined => {\n if (!keyByPath.has(target)) {\n const key = keyByPath.get(realpathOrSelf(target));\n if (key === undefined) return undefined;\n keyByPath.set(target, key);\n }\n return keyByPath.get(target);\n };\n const outside = new Set<string>();\n\n const dependencies = new Map<string, Set<string>>();\n /** importer → imported file → the names imported, and those among them that can carry a change. */\n const imported = new Map<string, Map<string, { readonly all: Set<string>; readonly changing: Set<string> }>>();\n const loaded = new Map<string, Loaded>();\n const warnings: ComputedImportWarning[] = [];\n const checked = new Set<string>();\n const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };\n const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile, file }) => {\n const from = relativeTo(config.rootDir, file);\n const checker = program.getTypeChecker();\n const imports = collectImports(ts, program, sourceFile, changeOracleFor(ts, checker, policyFor(ts, checker, config)));\n const targets = new Map<string, { readonly all: Set<string>; readonly changing: Set<string> }>();\n for (const edge of imports.edges) {\n if ((options.valueOnly && edge.typeOnly) || outside.has(edge.target)) continue;\n const to = keyOfTarget(policyFor(ts, checker, config).zones.virtualPaths.get(edge.target) ?? edge.target);\n if (to === undefined) outside.add(edge.target);\n if (to === undefined || to === from) continue;\n let names = targets.get(to);\n if (!names) {\n names = { all: new Set(), changing: new Set() };\n targets.set(to, names);\n }\n names.all.add(edge.name);\n if (edge.carriesChange) names.changing.add(edge.name);\n }\n dependencies.set(from, new Set(targets.keys()));\n imported.set(from, targets);\n loaded.set(from, { ts, program, sourceFile });\n for (const computed of imports.computed) {\n const position = svelteFor(checker)?.position(sourceFile.fileName, computed);\n if (position !== null) warnings.push({ kind: 'computed-import', file: from, ...computed, ...position });\n }\n if (!fromBaseline && checkSourceFile({ ts, program, config, sourceFile }).length > 0) checked.add(from);\n });\n if (walk.status !== 'ok') {\n logWalkFailure(options.log, 'refactor', walk);\n return 2;\n }\n\n const nodes = [...dependencies.keys()];\n const tasks = fromBaseline ? new Set(nodes.filter((file) => Object.hasOwn(baseline.counts, file) && hasFindings(baseline.counts[file]))) : checked;\n warnings.sort((a, b) => (a.file !== b.file ? (a.file < b.file ? -1 : 1) : a.line - b.line || a.column - b.column));\n // What cutting an import costs: a name that cannot change (an interface, a constant) is cheap to move\n // to a file of its own, so the imports named as closing a group are the ones made of such names.\n const cutCost = (from: string, to: string): number => {\n const names = imported.get(from)?.get(to);\n return names ? names.changing.size * CHANGING_NAME_COST + (names.all.size - names.changing.size) : 1;\n };\n const plan = planRefactor({\n files: nodes,\n dependencies,\n tasks,\n maxGroupSize,\n weight: cutCost,\n carriesChange: (from, to) => (imported.get(from)?.get(to)?.changing.size ?? 1) > 0,\n });\n const closing = (edges: readonly PlanEdge[], which: 'all' | 'changing'): ClosingImport[] => {\n return edges.map(({ from, to }) => ({ from, to, names: [...(imported.get(from)?.get(to)?.[which] ?? [])].sort() }));\n };\n const remaining = (group: CircularGroup): RemainingGroup => ({\n size: group.size,\n files: group.files,\n tasks: group.tasks,\n tooLarge: group.tooLarge,\n closingEdges: closing(group.closingEdges, 'changing'),\n ...(group.tooLarge ? internalOrder(group, loaded, config, keyOfTarget, maxGroupSize) : {}),\n });\n const cycles = plan.cycles.map((cycle): ReportedGroup => {\n const split = cycle.split;\n return {\n size: cycle.size,\n files: cycle.files,\n tasks: cycle.tasks,\n tooLarge: cycle.tooLarge,\n closingEdges: closing(cycle.closingEdges, 'all'),\n ...(split ? { split: { droppedEdges: split.droppedEdges, keptEdges: split.keptEdges, groups: split.groups.map(remaining) } } : {}),\n };\n });\n const report: RefactorReport = {\n waves: plan.waves,\n cycles,\n warnings,\n summary: {\n files: nodes.length,\n edges: [...dependencies.values()].reduce((sum, targets) => sum + targets.size, 0),\n tasks: tasks.size,\n items: plan.waves.reduce((sum, wave) => sum + wave.length, 0),\n ignored: resolved.files.length - files.length,\n taskSource: fromBaseline ? 'baseline' : 'check',\n baseline: fromBaseline ? baselineFile : null,\n valueOnly: options.valueOnly,\n maxGroupSize,\n },\n };\n if (options.json) options.log(JSON.stringify(report, null, 2));\n else for (const line of formatReport(report)) options.log(line);\n return 0;\n}\n","// The calls of one source file, between declarations (no ESLint). Files that import each other in a\n// circle usually do not call each other in a circle, so inside a circular-import group the order is\n// taken from the declarations: `c.ts#load` before `d.ts#save` when `save` calls `load`.\n//\n// A declaration is named by where it sits at the top of its file: `load`, `Store.load` (a class\n// member), `Config.read` (inside a namespace), `default` (an unnamed default export), and\n// TOP_LEVEL for statements that belong to no declaration. Code nested inside a declaration (a\n// callback, an inner function) belongs to it. The callee of a call is what TrustPolicy.calleeDeclaration\n// resolves it to; a call counts only when the callee can change (change.ts): a call through an\n// interface member, to a `.d.ts` declaration or to a function with a frozen Result contract does not.\nimport { svelteForSource } from './svelte.js';\nimport type * as TS from 'typescript';\nimport type { TrustPolicy } from '../eslint/policy.js';\nimport type { TypeScript } from '../eslint/typescript.js';\nimport type { ChangeOracle } from './change.js';\n\n/** The name of the statements of a file that belong to no declaration. */\nexport const TOP_LEVEL = '(top level)';\n\n/** One call site. */\nexport interface CallEdge {\n /** The declaration the call is written in. */\n readonly from: string;\n /** File name, as the program names it, of the file that declares the callee. */\n readonly targetFile: string;\n /** The declaration called, named within `targetFile`. */\n readonly to: string;\n}\n\nfunction memberName(ts: TypeScript, member: TS.ClassElement): string | undefined {\n if (ts.isConstructorDeclaration(member)) return 'constructor';\n const name = member.name;\n if (!name) return undefined;\n return ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : undefined;\n}\n\n/** `chain[index]` is a statement of the file or of a namespace body; the nodes after it lead down to the node being named. */\nfunction nameIn(ts: TypeScript, chain: readonly TS.Node[], index: number, prefix: string): string | null {\n const statement = chain[index];\n if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) return null;\n if (ts.isFunctionDeclaration(statement)) return prefix + (statement.name?.text ?? 'default');\n if (ts.isClassDeclaration(statement)) {\n const owner = prefix + (statement.name?.text ?? 'default');\n const member = chain.at(index + 1);\n const name = member && ts.isClassElement(member) ? memberName(ts, member) : undefined;\n return name === undefined ? owner : `${owner}.${name}`;\n }\n if (ts.isVariableStatement(statement)) {\n const declaration = chain.at(index + 2);\n return prefix + (declaration && ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) ? declaration.name.text : TOP_LEVEL);\n }\n if (ts.isModuleDeclaration(statement)) {\n const inner = `${prefix}${statement.name.text}.`;\n const body = chain.at(index + 1);\n // `namespace A.B {}` nests a ModuleDeclaration directly; `namespace A {}` has a block of statements.\n if (body && ts.isModuleDeclaration(body)) return nameIn(ts, chain, index + 1, inner);\n if (body && ts.isModuleBlock(body) && chain.length > index + 2) return nameIn(ts, chain, index + 2, inner);\n return prefix + statement.name.text;\n }\n if (ts.isExportAssignment(statement)) return `${prefix}default`;\n return prefix + TOP_LEVEL;\n}\n\n/** The declaration a node belongs to; null for the file itself and for a node inside a type or an enum. */\nexport function declarationOf(ts: TypeScript, node: TS.Node): string | null {\n const chain: TS.Node[] = [];\n for (let current = node; !ts.isSourceFile(current); current = current.parent) chain.push(current);\n if (chain.length === 0) return null;\n chain.reverse();\n // The converter's render function is a scope, not a user declaration.\n const virtual = svelteForSource(node.getSourceFile());\n const render = virtual && chain.findIndex(part => ts.isFunctionDeclaration(part) && part.name?.text === '$$render');\n const index = typeof render === 'number' && render >= 0 ? render + 2 : 0;\n return index < chain.length ? nameIn(ts, chain, index, '') : TOP_LEVEL;\n}\n\n/** The declaration at a 1-based line and column, as findings report them; TOP_LEVEL when there is none. */\nexport function declarationAt(ts: TypeScript, sourceFile: TS.SourceFile, line: number, column: number): string {\n const generated = svelteForSource(sourceFile)?.generatedPositions(sourceFile.fileName, { line, column })[0];\n const position = ts.getPositionOfLineAndCharacter(sourceFile, (generated?.line ?? line) - 1, (generated?.column ?? column) - 1);\n let node: TS.Node = sourceFile;\n for (;;) {\n const child: TS.Node | undefined = ts.forEachChild(node, (candidate) => (candidate.getStart(sourceFile) <= position && position < candidate.end ? candidate : undefined));\n if (!child) break;\n node = child;\n }\n return declarationOf(ts, node) ?? TOP_LEVEL;\n}\n\n/** Every call and `new` of the file whose callee is a declaration that can change, one edge per call site. */\nexport function collectCalls(ts: TypeScript, policy: TrustPolicy, change: ChangeOracle, sourceFile: TS.SourceFile): CallEdge[] {\n const calls: CallEdge[] = [];\n const visit = (node: TS.Node): void => {\n if ((ts.isCallExpression(node) && node.expression.kind !== ts.SyntaxKind.ImportKeyword) || ts.isNewExpression(node)) {\n const from = declarationOf(ts, node);\n const callee = from === null ? null : policy.calleeDeclaration(node);\n if (from !== null && callee && change.declarationCanChange(callee.declaration)) {\n const to = declarationOf(ts, callee.declaration);\n if (to !== null) calls.push({ from, targetFile: callee.declaration.getSourceFile().fileName, to });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return calls;\n}\n","// What the refactor can change, as the importers and callers of a declaration see it. An import or a\n// call orders two files only when a change can travel through it:\n// - a function, method, accessor or constructor with a body can change: its inferred types follow\n// what it calls, and the refactor moves its failures into its return type. A written return type\n// that is a Result from @noego/trust is a frozen contract: that function cannot change;\n// - an interface, a type alias, an annotated variable or property, and a signature without a body\n// are declared types: they change only through what they mention (`typeof load`, a class);\n// - an enum, a literal constant and anything declared in a `.d.ts` file cannot change;\n// - a class can change when a member or its base class can, a module when one of its exports can;\n// - whatever these rules do not cover can change. That is the safe answer: the edge is kept.\n// Runs on TypeScript alone (no ESLint).\nimport type * as TS from 'typescript';\nimport type { TrustPolicy } from '../eslint/policy.js';\nimport type { TypeScript } from '../eslint/typescript.js';\n\nexport class ChangeOracle {\n private readonly known = new Map<TS.Node, boolean>();\n /** Declarations being judged right now: meeting one again (a type that mentions itself) assumes \"cannot change\". */\n private readonly open = new Set<TS.Node>();\n private assumptions = 0;\n\n constructor(\n private readonly ts: TypeScript,\n private readonly checker: TS.TypeChecker,\n private readonly policy: TrustPolicy,\n ) {}\n\n /** Can what the symbol names change? Follows an import to what it imports; a symbol nothing declares can. */\n symbolCanChange(symbol: TS.Symbol | undefined): boolean {\n if (!symbol) return true;\n const target = symbol.flags & this.ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;\n const declarations = target.declarations ?? [];\n return declarations.length === 0 || declarations.some((declaration) => this.declarationCanChange(declaration));\n }\n\n declarationCanChange(declaration: TS.Node): boolean {\n const known = this.known.get(declaration);\n if (known !== undefined) return known;\n if (this.open.has(declaration)) {\n this.assumptions += 1;\n return false;\n }\n this.open.add(declaration);\n const before = this.assumptions;\n const result = this.judge(declaration);\n this.open.delete(declaration);\n // \"Cannot change\" that leaned on an assumption is final only once nothing is being judged anymore.\n if (result || this.assumptions === before || this.open.size === 0) this.known.set(declaration, result);\n return result;\n }\n\n private judge(node: TS.Node): boolean {\n const ts = this.ts;\n // A `.d.ts` file is not what is being refactored.\n if (node.getSourceFile().isDeclarationFile) return false;\n if (ts.isSourceFile(node)) return this.exportsCanChange(node);\n if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return this.mentionsChange(node);\n if (ts.isEnumDeclaration(node) || ts.isEnumMember(node) || ts.isTypeParameterDeclaration(node)) return false;\n if (ts.isFunctionLike(node)) {\n const body = (node as { readonly body?: TS.Node }).body;\n return body ? !this.frozen(node) : this.mentionsChange(node);\n }\n if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isParameter(node)) {\n if (node.type) return this.mentionsChange(node.type);\n if (ts.isPropertySignature(node)) return false;\n return node.initializer ? this.expressionCanChange(node.initializer) : true;\n }\n if (ts.isPropertyAssignment(node)) return this.expressionCanChange(node.initializer);\n if (ts.isExportAssignment(node)) return this.expressionCanChange(node.expression);\n if (ts.isClassLike(node)) {\n const base = (node.heritageClauses ?? []).filter((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);\n return base.some((clause) => this.mentionsChange(clause)) || node.members.some((member) => this.memberCanChange(member));\n }\n return true;\n }\n\n private memberCanChange(member: TS.ClassElement): boolean {\n const ts = this.ts;\n if (ts.isClassStaticBlockDeclaration(member) || ts.isSemicolonClassElement(member)) return false;\n return this.declarationCanChange(member);\n }\n\n private exportsCanChange(sourceFile: TS.SourceFile): boolean {\n const module = this.checker.getSymbolAtLocation(sourceFile);\n // Not a module (no import or export): nothing to import from it.\n if (!module) return false;\n return this.checker.getExportsOfModule(module).some((exported) => this.symbolCanChange(exported));\n }\n\n /** A written return type that is a Result (or a promise of one) and mentions nothing that can change. */\n private frozen(node: TS.SignatureDeclaration): boolean {\n if (!node.type) return false;\n const written = this.checker.getTypeFromTypeNode(node.type);\n const awaited = this.checker.getAwaitedType(written) ?? written;\n return this.policy.isResultType(awaited) && !this.mentionsChange(node.type);\n }\n\n /** The type of a value without a written type: fixed for a literal, open for a call, a name or anything computed. */\n private expressionCanChange(expression: TS.Expression): boolean {\n const ts = this.ts;\n if (ts.isParenthesizedExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) {\n return this.expressionCanChange(expression.expression);\n }\n if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) {\n return ts.isConstTypeReference(expression.type) ? this.expressionCanChange(expression.expression) : this.mentionsChange(expression.type);\n }\n if (ts.isLiteralExpression(expression) || ts.isTemplateExpression(expression)) return false;\n const kind = expression.kind;\n if (kind === ts.SyntaxKind.TrueKeyword || kind === ts.SyntaxKind.FalseKeyword || kind === ts.SyntaxKind.NullKeyword) return false;\n if (ts.isPrefixUnaryExpression(expression)) return this.expressionCanChange(expression.operand);\n if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression) || ts.isClassExpression(expression)) return this.declarationCanChange(expression);\n if (ts.isArrayLiteralExpression(expression)) {\n return expression.elements.some((element) => ts.isSpreadElement(element) || this.expressionCanChange(element));\n }\n if (ts.isObjectLiteralExpression(expression)) return expression.properties.some((property) => this.declarationCanChange(property));\n return true;\n }\n\n /** Does a written type (or a declaration made of written types) name something that can change? */\n private mentionsChange(node: TS.Node): boolean {\n const ts = this.ts;\n const visit = (child: TS.Node): boolean => {\n if (ts.isTypeReferenceNode(child) && this.symbolCanChange(this.named(child.typeName))) return true;\n if (ts.isTypeQueryNode(child) && this.symbolCanChange(this.named(child.exprName))) return true;\n if (ts.isExpressionWithTypeArguments(child)) {\n const expression = child.expression;\n if (this.symbolCanChange(this.checker.getSymbolAtLocation(ts.isPropertyAccessExpression(expression) ? expression.name : expression))) return true;\n }\n if (ts.isImportTypeNode(child)) {\n const name = child.qualifier ?? (ts.isLiteralTypeNode(child.argument) ? child.argument.literal : undefined);\n if (!name || this.symbolCanChange(ts.isStringLiteral(name) ? this.checker.getSymbolAtLocation(name) : this.named(name as TS.EntityName))) return true;\n }\n return ts.forEachChild(child, visit) ?? false;\n };\n return visit(node);\n }\n\n private named(name: TS.EntityName): TS.Symbol | undefined {\n return this.checker.getSymbolAtLocation(this.ts.isQualifiedName(name) ? name.right : name);\n }\n}\n\nconst oracles = new WeakMap<TrustPolicy, ChangeOracle>();\n\n/** One oracle per policy (so per checker and config): its verdicts are cached across files. */\nexport function changeOracleFor(ts: TypeScript, checker: TS.TypeChecker, policy: TrustPolicy): ChangeOracle {\n let oracle = oracles.get(policy);\n if (!oracle) {\n oracle = new ChangeOracle(ts, checker, policy);\n oracles.set(policy, oracle);\n }\n return oracle;\n}\n","// The static imports of one source file, resolved with its program's checker (no ESLint):\n// - a named or default import, and a named re-export, points at the file that declares the name,\n// so a barrel (`export { a } from './a'`) is looked through instead of becoming an edge itself;\n// - `import * as`, `export *`, `import x = require()`, a bare `import './x'` and `import('./x')`\n// point at the module file;\n// - `import('./x').T` in a type position counts as a type-only import;\n// - `import(expression)` with a computed specifier cannot be followed and is returned separately.\n// Targets are the program's file names; the caller keeps the ones that belong to its graph.\n// With a ChangeOracle every edge also says whether a change can travel through it (change.ts).\nimport type * as TS from 'typescript';\nimport type { TypeScript } from '../eslint/typescript.js';\nimport type { ChangeOracle } from './change.js';\nimport { startOf } from './check-file.js';\n\n/** The `name` of an edge to a module as a whole (`import * as`, `export *`, `import './x'`, `import('./x')`). */\nexport const WHOLE_MODULE = '*';\n\nexport interface ImportEdge {\n /** File name, as the program names it, of the file depended on. */\n readonly target: string;\n /** Written as type-only (`import type`, `export type`, `{ type X }`, or an `import()` type). */\n readonly typeOnly: boolean;\n /** The imported name as its module exports it (`default` for a default import), or WHOLE_MODULE. */\n readonly name: string;\n /**\n * Can a change of what is imported reach this file? False for an interface, a constant, a function\n * with a frozen Result contract, an import that binds nothing… Always true without a ChangeOracle.\n */\n readonly carriesChange: boolean;\n}\n\n/** An `import(...)` whose specifier is not a string literal. `line`/`column` are 1-based. */\nexport interface ComputedImport {\n readonly line: number;\n readonly column: number;\n /** Source text of the specifier expression. */\n readonly specifier: string;\n}\n\nexport interface FileImports {\n readonly edges: readonly ImportEdge[];\n readonly computed: readonly ComputedImport[];\n}\n\nconst resolutionCaches = new WeakMap<TS.Program, TS.ModuleResolutionCache>();\n\nfunction resolutionCache(ts: TypeScript, program: TS.Program): TS.ModuleResolutionCache {\n let cache = resolutionCaches.get(program);\n if (!cache) {\n cache = ts.createModuleResolutionCache(program.getCurrentDirectory(), (name) => name, program.getCompilerOptions());\n resolutionCaches.set(program, cache);\n }\n return cache;\n}\n\nfunction declarationFiles(symbol: TS.Symbol | undefined): string[] {\n return [...new Set((symbol?.declarations ?? []).map((declaration) => declaration.getSourceFile().fileName))];\n}\n\n/** What one import resolves to: the file(s) depended on, and whether a change can come through. */\ninterface Imported {\n readonly files: readonly string[];\n readonly carriesChange: boolean;\n}\n\nexport function collectImports(ts: TypeScript, program: TS.Program, sourceFile: TS.SourceFile, change?: ChangeOracle): FileImports {\n const checker = program.getTypeChecker();\n const edges: ImportEdge[] = [];\n const computed: ComputedImport[] = [];\n\n const add = (imported: Imported, name: string, typeOnly: boolean): void => {\n for (const target of imported.files) edges.push({ target, typeOnly, name, carriesChange: imported.carriesChange });\n };\n\n /** The file(s) of the module a specifier names; none for a package without sources or an unresolved import. */\n const moduleFiles = (specifier: TS.Expression): string[] => {\n const declared = declarationFiles(checker.getSymbolAtLocation(specifier));\n if (declared.length > 0 || !ts.isStringLiteralLike(specifier)) return declared;\n // A file with no import/export is not a module to the checker (`import './polyfill'`): resolve it by name.\n const resolved = ts.resolveModuleName(specifier.text, sourceFile.fileName, program.getCompilerOptions(), ts.sys, resolutionCache(ts, program));\n return resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : [];\n };\n\n /** The module as a whole: a change comes through when one of its exports can change. */\n const wholeModule = (specifier: TS.Expression): Imported => {\n return { files: moduleFiles(specifier), carriesChange: change ? change.symbolCanChange(checker.getSymbolAtLocation(specifier)) : true };\n };\n\n /** An import that binds no name (`import './x'`, `import {} from './x'`): the module is loaded, nothing of it is used. */\n const loadedOnly = (specifier: TS.Expression): Imported => {\n return { files: moduleFiles(specifier), carriesChange: change === undefined };\n };\n\n /** The file(s) declaring an imported name, looking through re-exports; the module file when the name does not resolve. */\n const declaring = (name: TS.Node, specifier: TS.Expression): Imported => {\n const symbol = checker.getSymbolAtLocation(name);\n const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;\n const declared = declarationFiles(target);\n if (declared.length === 0) return { files: moduleFiles(specifier), carriesChange: true };\n return { files: declared, carriesChange: change ? change.symbolCanChange(target) : true };\n };\n\n const visitImport = (node: TS.ImportDeclaration): void => {\n const clause = node.importClause;\n if (!clause) {\n add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, false);\n return;\n }\n if (clause.name) add(declaring(clause.name, node.moduleSpecifier), 'default', clause.isTypeOnly);\n const bindings = clause.namedBindings;\n if (!bindings) return;\n if (ts.isNamespaceImport(bindings)) {\n add(wholeModule(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);\n return;\n }\n // `import {} from './x'` still loads the module.\n if (bindings.elements.length === 0) add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);\n for (const element of bindings.elements) {\n add(declaring(element.name, node.moduleSpecifier), (element.propertyName ?? element.name).text, clause.isTypeOnly || element.isTypeOnly);\n }\n };\n\n const visitExport = (node: TS.ExportDeclaration, specifier: TS.Expression): void => {\n const clause = node.exportClause;\n if (!clause || !ts.isNamedExports(clause)) {\n add(wholeModule(specifier), WHOLE_MODULE, node.isTypeOnly);\n return;\n }\n if (clause.elements.length === 0) add(loadedOnly(specifier), WHOLE_MODULE, node.isTypeOnly);\n for (const element of clause.elements) {\n add(declaring(element.name, specifier), (element.propertyName ?? element.name).text, node.isTypeOnly || element.isTypeOnly);\n }\n };\n\n const visitImportType = (node: TS.ImportTypeNode): void => {\n if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal)) return;\n const specifier = node.argument.literal;\n let name = node.qualifier;\n while (name && ts.isQualifiedName(name)) name = name.left;\n if (name) add(declaring(name, specifier), name.text, true);\n else add(wholeModule(specifier), WHOLE_MODULE, true);\n };\n\n const visitDynamicImport = (node: TS.CallExpression): void => {\n const specifier = node.arguments.at(0);\n if (!specifier) return;\n if (ts.isStringLiteralLike(specifier)) add(wholeModule(specifier), WHOLE_MODULE, false);\n else computed.push({ ...startOf(ts, sourceFile, specifier), specifier: specifier.getText(sourceFile) });\n };\n\n const visit = (node: TS.Node): void => {\n if (ts.isImportDeclaration(node)) visitImport(node);\n else if (ts.isExportDeclaration(node) && node.moduleSpecifier) visitExport(node, node.moduleSpecifier);\n else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {\n add(wholeModule(node.moduleReference.expression), WHOLE_MODULE, node.isTypeOnly);\n } else if (ts.isImportTypeNode(node)) visitImportType(node);\n else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) visitDynamicImport(node);\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return { edges, computed };\n}\n","// Dependency-ordered refactor plan over a file import graph (no TypeScript, no ESLint):\n// 1. strongly connected components (Tarjan) become units: a circular-import group changes together;\n// 2. the condensed graph is layered into waves: a unit's wave comes after the waves of everything\n// it imports, so the leaves are wave one and units of one wave can be refactored in parallel;\n// 3. only files with findings (\"tasks\") are work; a finding-free file is not in the plan, but the\n// order it imposes is kept: its importers still come after its imports;\n// 4. every circular group names a small set of edges that close its cycles, and a group above the\n// size threshold is planned again without the edges that cannot carry a change.\n// File names are opaque keys here (the command uses baseline keys, and `file#declaration` keys for\n// the call graph inside a group).\n\n/** One agent's work: a file, or the files of one circular-import group that must change together. */\nexport type WorkItem = string | string[];\n\n/** `from` depends on `to`: a file imports a file, or a declaration calls a declaration. */\nexport interface PlanEdge {\n readonly from: string;\n readonly to: string;\n}\n\nexport interface CircularGroup {\n readonly size: number;\n /** Every file of the cycle, sorted. */\n readonly files: readonly string[];\n /** The files of the cycle that have findings (the group's work item), sorted. */\n readonly tasks: readonly string[];\n /** More files than `maxGroupSize`: too large for one unit of work. */\n readonly tooLarge: boolean;\n /** Edges inside the group that close its cycles: without them the group has no cycle. A small set, not always the smallest. */\n readonly closingEdges: readonly PlanEdge[];\n /** Only on a too-large group planned with `carriesChange`: what is left of it. */\n readonly split?: GroupSplit;\n}\n\n/** What is left of a too-large group without the edges that cannot carry a change. */\nexport interface GroupSplit {\n /** Edges inside the group that cannot carry a change: left out of the plan. */\n readonly droppedEdges: number;\n /** Edges inside the group that can carry a change. */\n readonly keptEdges: number;\n /** The circular groups still inside it (none when it fell apart), largest first; `closingEdges` are edges that carry a change. */\n readonly groups: readonly CircularGroup[];\n}\n\nexport interface RefactorPlan {\n /** `waves[n]` can start when `waves[n - 1]` is done; the items of one wave are independent. */\n readonly waves: WorkItem[][];\n /** Every circular-import group (two files or more), largest first. */\n readonly cycles: CircularGroup[];\n}\n\nexport interface RefactorPlanInput {\n /** Every file of the graph. */\n readonly files: readonly string[];\n /** file → the files it imports. Files not in `files` and self-imports are ignored. */\n readonly dependencies: ReadonlyMap<string, Iterable<string>>;\n /** The files that have findings. */\n readonly tasks: ReadonlySet<string>;\n /** A circular group with more files than this is flagged `tooLarge`. */\n readonly maxGroupSize: number;\n /** What cutting the edge `from` → `to` costs (1 when omitted). Closing edges are chosen among the cheap ones. */\n readonly weight?: (from: string, to: string) => number;\n /**\n * Can a change of `to` change `from` through this edge? When given, a too-large group is planned\n * again without the edges inside it that answer no.\n */\n readonly carriesChange?: (from: string, to: string) => boolean;\n}\n\ninterface Graph {\n readonly files: readonly string[];\n /** Per file index: the indexes of the files it imports, sorted, without itself. */\n readonly imports: readonly (readonly number[])[];\n}\n\nfunction indexGraph(files: readonly string[], dependencies: ReadonlyMap<string, Iterable<string>>): Graph {\n const sorted = [...new Set(files)].sort();\n const indexOf = new Map(sorted.map((file, index) => [file, index]));\n const imports = sorted.map((file, index) => {\n const targets = new Set<number>();\n for (const dependency of dependencies.get(file) ?? []) {\n const target = indexOf.get(dependency);\n if (target !== undefined && target !== index) targets.add(target);\n }\n return [...targets].sort((a, b) => a - b);\n });\n return { files: sorted, imports };\n}\n\n/**\n * Tarjan's algorithm, iterative (import chains can be thousands of files deep). Components come out\n * dependencies first: every component a component imports from is earlier in the list.\n */\nfunction components(graph: Graph): number[][] {\n const count = graph.files.length;\n const order = new Array<number>(count).fill(-1);\n const low = new Array<number>(count).fill(0);\n const onStack = new Array<boolean>(count).fill(false);\n const stack: number[] = [];\n const found: number[][] = [];\n let next = 0;\n\n for (let root = 0; root < count; root += 1) {\n if (order[root] !== -1) continue;\n // One frame per file being visited: the file and how many of its imports were followed.\n const frames: { readonly file: number; followed: number }[] = [];\n const open = (file: number): void => {\n order[file] = next;\n low[file] = next;\n next += 1;\n stack.push(file);\n onStack[file] = true;\n frames.push({ file, followed: 0 });\n };\n open(root);\n while (frames.length > 0) {\n const frame = frames[frames.length - 1];\n const targets = graph.imports[frame.file];\n if (frame.followed < targets.length) {\n const target = targets[frame.followed];\n frame.followed += 1;\n if (order[target] === -1) open(target);\n else if (onStack[target]) low[frame.file] = Math.min(low[frame.file], order[target]);\n continue;\n }\n frames.pop();\n if (frames.length > 0) {\n const parent = frames[frames.length - 1].file;\n low[parent] = Math.min(low[parent], low[frame.file]);\n }\n if (low[frame.file] !== order[frame.file]) continue;\n const component: number[] = [];\n for (;;) {\n const member = stack.pop() as number;\n onStack[member] = false;\n component.push(member);\n if (member === frame.file) break;\n }\n found.push(component.sort((a, b) => a - b));\n }\n }\n return found;\n}\n\n/** The strongly connected components of the import graph (each sorted), dependencies first. */\nexport function stronglyConnectedComponents(files: readonly string[], dependencies: ReadonlyMap<string, Iterable<string>>): string[][] {\n const graph = indexGraph(files, dependencies);\n return components(graph).map((component) => component.map((file) => graph.files[file]));\n}\n\nfunction firstFile(item: WorkItem): string {\n return typeof item === 'string' ? item : item[0];\n}\n\nfunction byName(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Can `to` be reached from `from` along `edges` (per file index: the indexes it points at)? */\nfunction reaches(edges: ReadonlyMap<number, ReadonlySet<number>>, from: number, to: number): boolean {\n const seen = new Set<number>([from]);\n const queue = [from];\n while (queue.length > 0) {\n const file = queue.pop() as number;\n if (file === to) return true;\n for (const target of edges.get(file) ?? []) {\n if (seen.has(target)) continue;\n seen.add(target);\n queue.push(target);\n }\n }\n return false;\n}\n\n/**\n * A small set of edges inside one component that close its cycles: without them the component has no\n * cycle. The smallest (or cheapest) such set is NP-hard to find, so this is a heuristic in two passes:\n * 1. order the members greedily (Eades, Lin and Smyth, with costs): a member that imports nothing\n * left goes last, a member nothing left imports goes first, otherwise the member whose imports\n * cost the most over its importers goes first; the edges that point backwards in that order\n * are candidates;\n * 2. put back every candidate that closes no cycle on its own, costliest first, so every edge that\n * stays closes a cycle and cheap edges are the ones cut.\n */\nfunction closingEdgesOf(graph: Graph, members: readonly number[], cost: (from: number, to: number) => number): [number, number][] {\n if (members.length < 2) return [];\n const inside = new Set(members);\n const out = new Map<number, number[]>(members.map((member) => [member, []]));\n const into = new Map<number, number[]>(members.map((member) => [member, []]));\n // Per member, over the members still to place: how many it imports and is imported by, and what those edges cost.\n const degree = new Map(members.map((member) => [member, { out: 0, in: 0, outCost: 0, inCost: 0 }]));\n const degreeOf = (member: number): { out: number; in: number; outCost: number; inCost: number } => {\n return degree.get(member) as { out: number; in: number; outCost: number; inCost: number };\n };\n for (const member of members) {\n for (const target of graph.imports[member]) {\n if (!inside.has(target)) continue;\n (out.get(member) as number[]).push(target);\n (into.get(target) as number[]).push(member);\n const edgeCost = cost(member, target);\n degreeOf(member).out += 1;\n degreeOf(member).outCost += edgeCost;\n degreeOf(target).in += 1;\n degreeOf(target).inCost += edgeCost;\n }\n }\n\n const left = new Set(members);\n const first: number[] = [];\n const last: number[] = [];\n const gap = (member: number): number => degreeOf(member).outCost - degreeOf(member).inCost;\n while (left.size > 0) {\n let sink: number | undefined;\n let source: number | undefined;\n let widest: number | undefined;\n for (const member of left) {\n if (degreeOf(member).out === 0) {\n sink = member;\n break;\n }\n if (source !== undefined) continue;\n if (degreeOf(member).in === 0) source = member;\n else if (widest === undefined || gap(member) > gap(widest)) widest = member;\n }\n const picked = (sink ?? source ?? widest) as number;\n if (sink !== undefined) last.push(picked);\n else first.push(picked);\n left.delete(picked);\n for (const target of out.get(picked) as number[]) {\n degreeOf(target).in -= 1;\n degreeOf(target).inCost -= cost(picked, target);\n }\n for (const importer of into.get(picked) as number[]) {\n degreeOf(importer).out -= 1;\n degreeOf(importer).outCost -= cost(importer, picked);\n }\n }\n\n // `first` then `last` reversed: importers before what they import. An edge pointing at an earlier member is a candidate.\n const position = new Map([...first, ...last.reverse()].map((member, index) => [member, index]));\n const kept = new Map<number, Set<number>>(members.map((member) => [member, new Set<number>()]));\n const candidates: [number, number][] = [];\n for (const member of members) {\n for (const target of out.get(member) as number[]) {\n if ((position.get(member) as number) > (position.get(target) as number)) candidates.push([member, target]);\n else (kept.get(member) as Set<number>).add(target);\n }\n }\n candidates.sort((a, b) => cost(b[0], b[1]) - cost(a[0], a[1]) || a[0] - b[0] || a[1] - b[1]);\n const closing: [number, number][] = [];\n for (const [from, to] of candidates) {\n if (reaches(kept, to, from)) closing.push([from, to]);\n else (kept.get(from) as Set<number>).add(to);\n }\n return closing.sort((a, b) => a[0] - b[0] || a[1] - b[1]);\n}\n\n/** Waves and circular groups of one indexed graph. */\nfunction planGraph(graph: Graph, input: RefactorPlanInput): { waves: WorkItem[][]; cycles: CircularGroup[] } {\n const units = components(graph);\n const unitOf = new Array<number>(graph.files.length).fill(0);\n units.forEach((members, unit) => {\n for (const member of members) unitOf[member] = unit;\n });\n const weight = input.weight;\n const cost = weight ? (from: number, to: number): number => weight(graph.files[from], graph.files[to]) : (): number => 1;\n\n // depth = how many task units lie on the longest import path below a unit. Units come dependencies\n // first, so each import's depth is final when its importer is reached. A finding-free unit adds\n // nothing itself and hands the depth of its imports on to its importers.\n const depth: number[] = [];\n const waves: WorkItem[][] = [];\n const cycles: CircularGroup[] = [];\n const work = units.map((members) => members.map((member) => graph.files[member]).filter((file) => input.tasks.has(file)));\n units.forEach((members, unit) => {\n let below = 0;\n for (const member of members) {\n for (const target of graph.imports[member]) {\n const imported = unitOf[target];\n if (imported !== unit) below = Math.max(below, depth[imported] + (work[imported].length > 0 ? 1 : 0));\n }\n }\n depth[unit] = below;\n const tasks = work[unit];\n if (members.length > 1) {\n const files = members.map((member) => graph.files[member]);\n const closingEdges = closingEdgesOf(graph, members, cost).map(([from, to]) => ({ from: graph.files[from], to: graph.files[to] }));\n cycles.push({ size: files.length, files, tasks, tooLarge: files.length > input.maxGroupSize, closingEdges });\n }\n if (tasks.length === 0) return;\n while (waves.length <= below) waves.push([]);\n waves[below].push(tasks.length === 1 ? tasks[0] : tasks);\n });\n\n for (const wave of waves) wave.sort((a, b) => byName(firstFile(a), firstFile(b)));\n cycles.sort((a, b) => b.size - a.size || byName(a.files[0], b.files[0]));\n return { waves, cycles };\n}\n\n/**\n * The plan of the import graph. With `carriesChange`, a circular group above `maxGroupSize` is shrunk\n * first: the edges inside it that cannot carry a change are left out and the graph is planned again,\n * so the waves hold what is left of the group (smaller groups and single files, in their own order).\n * `cycles` still lists the groups of the full graph; a group that was shrunk says what is left of it\n * in `split`. A group at or under the threshold, and every edge outside the too-large groups, is\n * planned as it is.\n */\nexport function planRefactor(input: RefactorPlanInput): RefactorPlan {\n const graph = indexGraph(input.files, input.dependencies);\n const full = planGraph(graph, input);\n const carriesChange = input.carriesChange;\n if (!carriesChange || !full.cycles.some((cycle) => cycle.tooLarge)) return full;\n\n const groupOf = new Map<string, number>();\n full.cycles.forEach((cycle, index) => {\n if (cycle.tooLarge) for (const file of cycle.files) groupOf.set(file, index);\n });\n const dropped = new Map<number, number>();\n const kept = new Map<number, number>();\n const imports = graph.imports.map((targets, file) => {\n const group = groupOf.get(graph.files[file]);\n if (group === undefined) return targets;\n return targets.filter((target) => {\n if (groupOf.get(graph.files[target]) !== group) return true;\n const carries = carriesChange(graph.files[file], graph.files[target]);\n const counts = carries ? kept : dropped;\n counts.set(group, (counts.get(group) ?? 0) + 1);\n return carries;\n });\n });\n const pruned = planGraph({ files: graph.files, imports }, input);\n const cycles = full.cycles.map((cycle, index) => {\n if (!cycle.tooLarge) return cycle;\n const groups = pruned.cycles.filter((left) => groupOf.get(left.files[0]) === index);\n return { ...cycle, split: { droppedEdges: dropped.get(index) ?? 0, keptEdges: kept.get(index) ?? 0, groups } };\n });\n return { waves: pruned.waves, cycles };\n}\n","#!/usr/bin/env node\n// trust — CLI for @noego/trust.\n//\n// trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig tsconfig.json] [--root <dir>]\n// trust baseline [paths…] [--config trust.config.json] [--baseline trust-baseline.json] [--update] [--tsconfig tsconfig.json] [--root <dir>]\n// trust check <paths…> [--strict] [--config trust.config.json] [--tsconfig tsconfig.json] [--root <dir>]\n// trust refactor [paths…] [--json] [--value-only] [--max-group <n>] [--config trust.config.json] [--baseline trust-baseline.json] [--tsconfig tsconfig.json] [--root <dir>]\nimport { runBaselineCommand } from './baseline-command.js';\nimport { runCheckCommand } from './check-command.js';\nimport { acquireRunLock, runLockDisabled } from './run-lock.js';\nimport { explain, formatExplanation } from './explain.js';\nimport { runRefactorCommand } from './refactor-command.js';\n\n\nconst USAGE = `Usage:\n trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]\n Print the origin each call on that line resolves to, and why it is (un)trusted: for failing\n (\"trust\" / \"distrust\") and for its types (\"trust_type\" / \"distrust_type\").\n Also prints every type claim starting on that line (type-claim): its kind and why it is a claim,\n and every untrusted value starting on it (untrusted-value): how it entered, the origin that\n declared its type, and whether its use is reported.\n trust baseline [paths...] [--config trust.config.json] [--baseline trust-baseline.json] [--update] [--tsconfig <path>] [--root <dir>]\n Check the files with TypeScript alone (no ESLint) and fail on trust violations not in the baseline.\n Files are found and skipped as in trust check; --update rewrites the baseline from the current findings.\n With paths, only the checked files' entries are reported as shrunk or rewritten by --update.\n trust check <paths...> [--strict] [--perf] [--json] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]\n Check with the native Rust engine (bundled Wasm fallback); .svelte conversion uses TypeScript in Node.\n Each file uses --tsconfig if given, else the first matching \"tsconfig\" entry of the trust config,\n else the nearest tsconfig.json above it.\n Files in the config's ignore zone are skipped. --strict also fails on written return types\n in every checked file; the config's \"strict\" globs do the same for the files they match.\n --perf adds performance warnings, which never fail the check. --json emits findings with severity.\n Exit codes: 0 clean or warnings only, 1 trust errors, 2 the check could not run.\n trust refactor [paths...] [--json] [--value-only] [--max-group <n>] [--config trust.config.json] [--baseline trust-baseline.json] [--tsconfig <path>] [--root <dir>]\n Print the order to refactor the files with findings in: waves of work items, leaves of the import\n graph first. The items of a wave can be done in parallel; a circular-import group is one item.\n Findings come from the baseline, or from a fresh check when there is no baseline file.\n --json prints { \"waves\": [[\"a.ts\", [\"b.ts\", \"c.ts\"]], [\"d.ts\"]], ... }; --value-only leaves\n type-only imports out of the graph. Every circular group lists the imports that close it.\n A circular group of more than --max-group <n> files (default 8) is too large for one item: the\n imports inside it that cannot carry a change (an interface, a constant, a written Result return\n type) are dropped; what is still too large gets an internal order of its declarations, callees\n first, and declarations that call each other in a circle are reported with the calls closing it.\n --root <dir> resolves the config's globs, tsconfig paths and baseline keys against <dir> instead of\n the config file's directory (for a config kept outside the project).`;\n\ninterface ParsedArgs {\n readonly positional: string[];\n readonly flags: Map<string, string | true>;\n}\n\n/** Flags that take no value. */\nconst BOOLEAN_FLAGS = new Set(['update', 'help', 'strict', 'json', 'value-only', 'perf']);\n\nfunction parseArgs(argv: readonly string[]): ParsedArgs {\n const positional: string[] = [];\n const flags = new Map<string, string | true>();\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n if (!arg.startsWith('--')) {\n positional.push(arg);\n continue;\n }\n const [name, inline] = arg.slice(2).split('=', 2);\n if (name === 'rs' || name === 'go') throw new Error('--rs and --go were removed; trust check uses the native engine automatically');\n if (!BOOLEAN_FLAGS.has(name) && !['config', 'tsconfig', 'root', 'baseline', 'max-group'].includes(name)) throw new Error(`unknown flag --${name}`);\n if (BOOLEAN_FLAGS.has(name) && inline !== undefined) throw new Error(`--${name} does not take a value`);\n if (inline !== undefined) flags.set(name, inline);\n else if (BOOLEAN_FLAGS.has(name)) flags.set(name, true);\n else {\n const value = argv[index + 1];\n if (value === undefined) throw new Error(`--${name} needs a value`);\n flags.set(name, value);\n index += 1;\n }\n }\n return { positional, flags };\n}\n\nfunction stringFlag(flags: Map<string, string | true>, name: string): string | undefined {\n const value = flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction parseLocation(location: string): { file: string; line: number; column?: number } {\n const match = /^(.*?):(\\d+)(?::(\\d+))?$/.exec(location);\n if (!match) throw new Error(`expected <file>:<line>[:<column>], got \"${location}\"`);\n return { file: match[1], line: Number(match[2]), column: match[3] ? Number(match[3]) : undefined };\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n const [command, ...rest] = argv;\n const { positional, flags } = parseArgs(rest);\n const cwd = process.cwd();\n const configFile = stringFlag(flags, 'config') ?? 'trust.config.json';\n if (!command || command === 'help' || flags.has('help')) {\n console.log(USAGE);\n return command ? 0 : 1;\n }\n if (command === 'explain') {\n if (positional.length !== 1) throw new Error('explain takes exactly one <file>:<line>[:<column>]');\n const location = parseLocation(positional[0]);\n const explained = explain({ cwd, configFile, tsconfig: stringFlag(flags, 'tsconfig'), root: stringFlag(flags, 'root'), ...location });\n if (explained.kind !== 'explained') {\n console.error(`trust explain: ${explained.message}`);\n return 2;\n }\n console.log(formatExplanation(explained.explanation));\n return 0;\n }\n if (command === 'baseline') {\n return runBaselineCommand({\n cwd,\n paths: positional,\n configFile,\n baselineFile: stringFlag(flags, 'baseline'),\n update: flags.get('update') === true,\n tsconfig: stringFlag(flags, 'tsconfig'),\n root: stringFlag(flags, 'root'),\n log: (line) => console.log(line),\n });\n }\n if (command === 'check') {\n return runCheckCommand({\n cwd,\n paths: positional,\n configFile,\n strict: flags.get('strict') === true,\n tsconfig: stringFlag(flags, 'tsconfig'),\n root: stringFlag(flags, 'root'),\n perf: flags.get('perf') === true,\n json: flags.get('json') === true,\n log: (line) => console.log(line),\n });\n }\n if (command === 'refactor') {\n const maxGroup = stringFlag(flags, 'max-group');\n return runRefactorCommand({\n cwd,\n paths: positional,\n configFile,\n baselineFile: stringFlag(flags, 'baseline'),\n json: flags.get('json') === true,\n valueOnly: flags.get('value-only') === true,\n maxGroupSize: maxGroup === undefined ? undefined : Number(maxGroup),\n tsconfig: stringFlag(flags, 'tsconfig'),\n root: stringFlag(flags, 'root'),\n log: (line) => console.log(line),\n });\n }\n throw new Error(`unknown command \"${command}\"\\n${USAGE}`);\n}\n\nconst HEAVY_COMMANDS = new Set(['baseline', 'check', 'refactor']);\n\n/** Heavy commands queue behind any other Trust run on this machine (see run-lock.ts). */\nasync function runExclusive(argv: readonly string[]): Promise<number> {\n const [command] = argv;\n if (!command || !HEAVY_COMMANDS.has(command) || argv.includes('--help') || runLockDisabled()) return main(argv);\n const lock = await acquireRunLock({\n onWait: () => console.error('trust: another trust run is in progress on this machine; waiting for it to finish…'),\n });\n try {\n return await main(argv);\n } finally {\n await lock.release();\n }\n}\n\nrunExclusive(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (error: unknown) => {\n console.error(`trust: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 2;\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,YAAY,qBAAqB;AAC1C,SAAS,QAAAA,OAAM,WAAAC,gBAAe;;;ACC9B,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,WAAAC,gBAAe;AAKxB,SAAS,iBAAiB;AAC1B,SAAS,cAAc;;;ACdvB,SAAS,YAAY,WAAW,cAAc,gBAAgB;AAC9D,SAAS,qBAAqB;AAC9B,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,qBAAqB;AASvB,SAAS,sBAAsB,UAAkB,MAAc,OAAa,MAAqB;AACtG,MAAI,aAAa,YAAY,SAAS,QAAS,QAAO;AACtD,MAAI,aAAa,WAAW,SAAS,WAAW,SAAS,MAAO,QAAO;AACvE,MAAI,aAAa,WAAW,SAAS,MAAO,QAAO;AACnD,SAAO;AACT;AAGO,IAAM,uBAAuB;AAE7B,SAAS,oBAAoB,SAAiC;AACnE,MAAI,CAAC,WAAW,CAAC,uBAAuB,KAAK,OAAO,EAAG,QAAO;AAC9D,QAAM,CAAC,OAAO,KAAK,IAAI,QAAQ,MAAM,GAAG,EAAE,IAAI,MAAM;AACpD,QAAM,CAAC,cAAc,YAAY,IAAI,qBAAqB,MAAM,GAAG,EAAE,IAAI,MAAM;AAC/E,SAAO,QAAQ,gBAAiB,UA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K,IAAI;AAC9G,QAAM,OAAO,MAAM,eAAe;AAAA,IAChC,QAAQ,MAAM,QAAQ,MAAM,yFAAoF;AAAA,EAClH,CAAC;AACD,MAAI;AACF,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,UAAE;AACA,UAAM,KAAK,QAAQ;AAAA,EACrB;AACF;AAEA,aAAa,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EAClC,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAmB;AAClB,YAAQ,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChF,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["join","resolve","readFileSync","resolve","path","readFileSync","resolve","resolve","join","existsSync","resolve","resolve","existsSync","statSync","join","resolve","resolve","resolve","found","existsSync","join","resolve","byName","resolve","existsSync","join"]}
1
+ {"version":3,"sources":["../../src/cli/baseline-command.ts","../../src/cli/native-check.ts","../../src/cli/native-engine.ts","../../src/cli/check-command.ts","../../src/cli/run-lock.ts","../../src/cli/explain.ts","../../src/cli/refactor-command.ts","../../src/core/call-graph.ts","../../src/core/change.ts","../../src/core/import-graph.ts","../../src/core/refactor-plan.ts","../../src/cli/index.ts"],"sourcesContent":["// `trust baseline [paths…] [--update] [--tsconfig <path>] [--root <dir>]` — runs the native engine\n// (as `trust check` does, without the strict rules) over the files `trust check` resolves, and compares\n// the findings against trust-baseline.json (file + rule + origin → count). Files in the config's\n// `ignore` zone are skipped. With named paths only the checked files' entries can go stale or be\n// rewritten by --update; with no paths the run covers the whole baseline.\nimport { existsSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport {\n compareToBaseline,\n describeBaselineDelta,\n readBaseline,\n serializeBaseline,\n updateBaseline,\n WHOLE_BASELINE,\n type BaselineScope,\n} from '../core/baseline.js';\nimport { emptyTrustConfig } from '../core/check-file.js';\nimport { BOUNDARY_RULE, DROPPED_RESULT_RULE, TYPE_CLAIM_RULE, UNTRUSTED_VALUE_RULE } from '../core/messages.js';\nimport { loadTrustConfig } from '../eslint/config.js';\nimport { Zones } from '../eslint/zones.js';\nimport { checkNative } from './native-check.js';\nimport { logUnmatchedGlobs, logWalkFailure, relativeTo, resolveFiles } from './source-files.js';\n\nexport interface BaselineCommandOptions {\n readonly cwd: string;\n /** Files or directories; the current directory when empty. */\n readonly paths: readonly string[];\n readonly configFile: string;\n readonly baselineFile?: string;\n readonly update: boolean;\n /** One tsconfig for every file, instead of the config's `tsconfig` entries or the nearest tsconfig.json. */\n readonly tsconfig?: string;\n /** Directory the config's paths resolve against, instead of the config file's directory. */\n readonly root?: string;\n readonly log: (line: string) => void;\n}\n\n/** The baseline's counts (none when the file does not exist), or why it could not be read. */\nexport { readBaseline };\n\n/** Returns the process exit code: 0 ok, 1 new violations, 2 could not run (TypeScript, an unloadable file, an unreadable baseline). */\nexport async function runBaselineCommand(options: BaselineCommandOptions): Promise<number> {\n const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ['.']);\n if ('missing' in resolved) {\n options.log(`trust baseline: no such file or directory: ${resolved.missing}`);\n return 2;\n }\n const configPath = resolve(options.cwd, options.configFile);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = existsSync(configPath)\n ? loadTrustConfig(configPath, { rootDir })\n : emptyTrustConfig(rootDir ?? options.cwd);\n logUnmatchedGlobs(options.log, 'baseline', config);\n const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, 'trust-baseline.json'));\n const zones = new Zones(config.rootDir, config.passthrough, config.ignore);\n const files = resolved.files.filter((file) => zones.zoneOf(file) !== 'ignore');\n // With named paths the run speaks only for the files it checked; with none it covers the whole tree.\n const scope: BaselineScope =\n options.paths.length === 0 ? WHOLE_BASELINE : { kind: 'files', files: new Set(files.map((file) => relativeTo(config.rootDir, file))) };\n\n // The native engine holds one compact program instead of TypeScript's (several GB on a large repo).\n const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };\n const { findings, walk } = await checkNative({ cwd: options.cwd, files, config, programs, strictFiles: [], log: options.log });\n if (walk.status !== 'ok') {\n logWalkFailure(options.log, 'baseline', walk);\n return 2;\n }\n\n // A whole-tree --update rewrites the file from scratch (and so also repairs an unreadable one).\n const baseline = options.update && scope.kind === 'all' ? { counts: {} } : readBaseline(baselineFile);\n if ('error' in baseline) {\n options.log(`trust baseline: could not read the baseline: ${baseline.error}`);\n return 2;\n }\n if (options.update) {\n const updated = updateBaseline(baseline.counts, findings, scope);\n writeFileSync(baselineFile, serializeBaseline(updated.counts));\n const kept = updated.kept > 0 ? ` Kept the entries of ${updated.kept} unchecked file(s).` : '';\n options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${files.length} checked file(s).${kept}`);\n return 0;\n }\n const { added, stale } = compareToBaseline(findings, baseline.counts, scope);\n if (stale.length > 0) {\n options.log(`${stale.length} baseline entr${stale.length === 1 ? 'y has' : 'ies have'} fewer findings now; run with --update to shrink the baseline.`);\n }\n if (added.length === 0) {\n options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${files.length} file(s)).`);\n return 0;\n }\n const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);\n options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);\n for (const delta of added) for (const line of describeBaselineDelta(delta)) options.log(` ${line}`);\n options.log('Guard each call (try/catch returning Result.err, or Trust.try), or trust its origin in trust.config.json.');\n const hasTypeClaims = added.some((delta) => delta.rule === TYPE_CLAIM_RULE);\n if (hasTypeClaims) options.log('Prove each claimed type (narrow or validate the value) instead of asserting it.');\n const hasUntrustedValues = added.some((delta) => delta.rule === UNTRUSTED_VALUE_RULE);\n if (hasUntrustedValues) {\n options.log('Validate each untrusted value (or keep it as `unknown` and narrow it), or add its origin to \"trust_type\" in trust.config.json.');\n }\n if (added.some((delta) => delta.rule === DROPPED_RESULT_RULE)) {\n options.log('Return each dropped failure (`if (!r.ok) return r;`) or handle it with Trust.decide.');\n }\n if (added.some((delta) => delta.rule === BOUNDARY_RULE)) {\n options.log('Decide every kind at each boundary (an exhaustive `switch`) and return plain data, or exclude it under \"boundaries\" in trust.config.json.');\n }\n const alsoShows = `${hasTypeClaims ? ', and why a line is a type claim' : ''}${hasUntrustedValues ? ', and where an untrusted value comes from' : ''}`;\n options.log(`\\`trust explain <file>:<line>\\` shows which origin a call resolves to${alsoShows}.`);\n return 1;\n}\n","// Default `trust check` engine. Node resolves files, trust config and strict files; Rust owns\n// tsconfig parsing, embedded standard libs, program construction and rules. One JSON request/reply.\n//\n// Two builds speak the same protocol: a platform binary from an optional npm package (preferred),\n// and the bundled Wasm fallback. Neither requires an end-user Rust toolchain or postinstall download.\n// Explicit TRUST_NATIVE_BIN / TRUST_NATIVE_WASM overrides and local development builds still work.\n// TRUST_NATIVE_ENGINE=wasm|binary forces one.\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { prepareSvelte, SvelteFileError, SvelteInputs } from '../core/svelte.js';\nimport { groupByTsconfig } from '../core/program.js';\nimport { loadTypeScript } from '../eslint/typescript.js';\nimport { decide } from '../eslint/policy.js';\nimport { spawnSync } from 'node:child_process';\nimport { Worker } from 'node:worker_threads';\nimport { nativeEngine } from './native-engine.js';\n\nimport type { Finding } from '../core/messages.js';\nimport { isRuleEnabled, type OptInRule, type TrustConfig } from '../eslint/config.js';\n\nimport { relativeTo, type ProgramOptions, type ProgramWalk } from './source-files.js';\n\nexport { nativeBinary, nativeWasm, nativeEngine, type NativeEngine } from './native-engine.js';\nexport const NATIVE_PROTOCOL_VERSION = 6;\n\n/** Stack of the wasm run's worker thread, in MB: the checker recurses deeply (ts-rust's own host uses 256). */\nconst WASM_STACK_SIZE_MB = 256;\n\nconst OPT_IN_RULES: readonly OptInRule[] = [];\n\ninterface NativeResponse {\n readonly version: number;\n readonly findings: readonly Finding[];\n readonly errors: readonly string[];\n readonly setupError: string | null;\n readonly stats: { readonly loadSeconds: number; readonly checkSeconds: number; readonly checkedFiles: number };\n}\n\nexport interface NativeCheckOptions {\n readonly cwd: string;\n /** Absolute paths of the files to check (already filtered by the ignore zone). */\n readonly files: readonly string[];\n readonly programs: ProgramOptions;\n readonly config: TrustConfig;\n /** Absolute paths of the files the strict rules also run on. */\n readonly strictFiles: readonly string[];\n readonly perf?: boolean;\n readonly log: (line: string) => void;\n}\n\ninterface EngineRun {\n /** 0: `output` is the JSON response. Else `output` (or `stderr`) says what went wrong. */\n readonly status: number;\n readonly output: string;\n readonly stderr: string;\n}\n\nfunction runBinary(binary: string, request: string, cwd: string): EngineRun {\n const result = spawnSync(binary, [], { cwd, input: request, encoding: 'utf8', maxBuffer: 1024 * 1024 * 1024 });\n if (result.error) return { status: -1, output: `trust-native could not run: ${result.error.message}`, stderr: '' };\n if (result.status !== 0) {\n return { status: result.status ?? -1, output: `trust-native exited with ${result.status ?? result.signal}: ${result.stderr.trim().split('\\n').slice(0, 5).join('\\n')}`, stderr: result.stderr };\n }\n return { status: 0, output: result.stdout, stderr: result.stderr };\n}\n\nfunction runWasm(wasmPath: string, request: string): Promise<EngineRun> {\n return new Promise((resolvePromise) => {\n const worker = new Worker(new URL('./wasm-worker.js', import.meta.url), {\n workerData: { wasmPath, request },\n resourceLimits: { stackSizeMb: WASM_STACK_SIZE_MB },\n });\n let result: EngineRun | undefined;\n worker.on('message', (message: { status: number; output: string; stderr: string }) => {\n result = message.status === 0 ? message : { status: message.status, output: `trust-native (wasm) failed with ${message.status}: ${message.output.trim().split('\\n').slice(0, 5).join('\\n')}`, stderr: message.stderr };\n });\n worker.on('error', (error) => {\n result ??= { status: -1, output: `trust-native (wasm) crashed: ${error.message}`, stderr: '' };\n });\n worker.on('exit', (code) => {\n resolvePromise(result ?? { status: -1, output: `trust-native (wasm) worker ended without a result (exit ${code})`, stderr: '' });\n });\n });\n}\n\n/** Reject stale engines and malformed/partial output rather than reporting a false clean check. */\nexport function validResponse(value: unknown): value is NativeResponse {\n if (!value || typeof value !== 'object') return false;\n const response = value as Record<string, unknown>;\n if (response.version !== NATIVE_PROTOCOL_VERSION || !Array.isArray(response.findings) || !Array.isArray(response.errors)) return false;\n if (response.setupError !== null && typeof response.setupError !== 'string') return false;\n if (!response.errors.every(error => typeof error === 'string')) return false;\n if (!response.findings.every(finding => finding && typeof finding === 'object'\n && ['file', 'rule', 'origin', 'message'].every(key => typeof finding[key] === 'string')\n && Number.isInteger(finding.line) && finding.line > 0 && Number.isInteger(finding.column) && finding.column > 0\n && (finding.severity === 'error' || finding.severity === 'warning'))) return false;\n const stats = response.stats as Record<string, unknown> | undefined;\n return !!stats && ['loadSeconds', 'checkSeconds', 'checkedFiles'].every(key => typeof stats[key] === 'number' && Number.isFinite(stats[key]) && (stats[key] as number) >= 0);\n}\n\n/** One request to the native engine; the findings come back unsorted. */\nexport async function checkNative(options: NativeCheckOptions): Promise<{ findings: Finding[]; walk: ProgramWalk }> {\n const { config } = options;\n if (options.files.length === 0) return { findings: [], walk: { status: 'ok' } };\n for (const rule of OPT_IN_RULES) {\n if (isRuleEnabled(config, rule)) {\n return { findings: [], walk: { status: 'setup-failed', message: `the native engine does not support the \"${rule}\" rule yet; this release cannot check this configuration safely` } };\n }\n }\n const engine = nativeEngine();\n if (!engine) {\n return {\n findings: [],\n walk: {\n status: 'setup-failed',\n message: 'the trust-native engine is missing: reinstall @noego/trust (it includes a Wasm fallback), unset TRUST_NATIVE_ENGINE if it forces an unavailable binary, or set TRUST_NATIVE_BIN / TRUST_NATIVE_WASM; for a checkout, build the engine in native/',\n },\n };\n }\n\n let svelte: ReturnType<typeof prepareSvelte>;\n let extraRoots: Record<string, string[]>;\n try {\n const needed = options.files.some(file => file.endsWith('.svelte') || readFileSync(file, 'utf8').includes('.svelte'));\n if (!needed) { svelte = new SvelteInputs(); extraRoots = {}; }\n else {\n const ts = loadTypeScript(options.cwd);\n svelte = prepareSvelte(ts, options.cwd, options.files, options.programs.tsconfig, options.programs.mappings);\n const grouping = groupByTsconfig(ts, options.cwd, options.files, options.programs.tsconfig, options.programs.mappings);\n if (grouping.kind !== 'grouped') return { findings: [], walk: { status: 'setup-failed', message: grouping.message } };\n extraRoots = Object.fromEntries([...grouping.groups].map(([owner, files]) => [owner ?? '', svelte.extraRoots(files)]));\n }\n } catch (error) {\n return { findings: [], walk: error instanceof SvelteFileError ? { status: 'file-errors', errors: [error.message] } : { status: 'setup-failed', message: error instanceof Error ? error.message : String(error) } };\n }\n const request = JSON.stringify({\n version: NATIVE_PROTOCOL_VERSION,\n cwd: options.cwd,\n rootDir: config.rootDir,\n files: options.files.map(file => svelte.generated(file)),\n virtualFiles: Object.fromEntries(svelte.virtual),\n virtualPaths: Object.fromEntries(svelte.paths),\n extraRoots,\n programs: options.programs,\n perf: options.perf ?? false,\n rules: { trustedState: isRuleEnabled(config, 'trusted-state'), typeClaim: isRuleEnabled(config, 'type-claim'), untrustedValue: isRuleEnabled(config, 'untrusted-value'), untrustedCallbacks: config.rules.untrustedCallbacks, droppedResult: isRuleEnabled(config, 'dropped-result'), redundantGuard: isRuleEnabled(config, 'redundant-guard'), finallyReturn: isRuleEnabled(config, 'finally-return'), resultLookalike: config.rules['result-lookalike'] },\n config: {\n levels: config.levels.map((level) => ({ source: level.source, trust: level.trust, distrust: level.distrust, typeTrust: level.typeTrust, typeDistrust: level.typeDistrust })),\n passthrough: config.passthrough.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns })),\n ignore: config.ignore.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns })),\n boundaries: config.boundaries.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns, index: group.index, exclude: group.exclude })),\n },\n strictFiles: options.strictFiles.map(file => svelte.generated(file)),\n });\n const started = Date.now();\n const result = engine.kind === 'binary' ? runBinary(engine.path, request, options.cwd) : await runWasm(engine.path, request);\n if (result.status !== 0) {\n return { findings: [], walk: { status: 'setup-failed', message: result.output } };\n }\n let response: NativeResponse;\n try {\n const value: unknown = JSON.parse(result.output);\n if (!validResponse(value)) throw new Error('Invalid engine response');\n response = value;\n } catch {\n return { findings: [], walk: { status: 'setup-failed', message: `trust-native (${engine.kind}) returned malformed output` } };\n }\n if (process.env.TRUST_NATIVE_DEBUG) {\n options.log(\n `trust native: ${engine.kind} engine checked ${response.stats.checkedFiles} file(s): load ${response.stats.loadSeconds.toFixed(1)}s, ` +\n `rules ${response.stats.checkSeconds.toFixed(1)}s, round trip ${((Date.now() - started) / 1000).toFixed(1)}s`,\n );\n if (result.stderr.trim()) options.log(result.stderr.trim());\n }\n if (response.setupError !== null) return { findings: [], walk: { status: 'setup-failed', message: response.setupError } };\n if (response.errors.length > 0) return { findings: [], walk: { status: 'file-errors', errors: response.errors.map(error => svelte.error(error)) } };\n const snippetTrusted = decide(config.levels, level => level, 'svelte.__renderSnippet', 'svelte').trusted && !('distrustedBy' in decide(config.levels, level => level, 'svelte.Snippet', 'svelte'));\n const findings = response.findings.flatMap(finding => {\n const file = resolve(config.rootDir, finding.file);\n const mapped = svelte.finding(file, finding, snippetTrusted);\n return mapped ? [{ ...mapped, file: svelte.paths.has(file) ? relativeTo(config.rootDir, svelte.original(file)) : finding.file }] : [];\n });\n return { findings, walk: { status: 'ok' } };\n}\n","import { accessSync, constants, readFileSync, statSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport type NativeEngine = { readonly kind: 'binary'; readonly path: string } | { readonly kind: 'wasm'; readonly path: string };\ntype Libc = 'glibc' | 'musl' | null;\n\n/**\n * Native executables ship for Apple-silicon macOS, x64 GNU/Linux and x64 Windows, each built natively on a\n * self-hosted runner. Intel macOS, arm64 Linux, musl and every other platform use Wasm.\n */\nexport function nativePlatformPackage(platform: string, arch: string, libc: Libc = null): string | null {\n if (platform === 'darwin' && arch === 'arm64') return '@noego/trust-darwin-arm64';\n if (platform === 'linux' && libc === 'glibc' && arch === 'x64') return '@noego/trust-linux-x64-gnu';\n if (platform === 'win32' && arch === 'x64') return '@noego/trust-win32-x64-msvc';\n return null;\n}\n\n// The GNU release job builds on Ubuntu 24.04 (self-hosted). Older glibc must use Wasm, not a failing executable.\nexport const NATIVE_MINIMUM_GLIBC = '2.39';\n\nexport function supportsNativeGlibc(version: string | null): boolean {\n if (!version || !/^\\d+\\.\\d+(?:\\.\\d+)?$/.test(version)) return false;\n const [major, minor] = version.split('.').map(Number);\n const [minimumMajor, minimumMinor] = NATIVE_MINIMUM_GLIBC.split('.').map(Number);\n return major > minimumMajor || (major === minimumMajor && minor >= minimumMinor);\n}\n\nfunction runtimeLinux(platform: string): { libc: Libc; version: string | null } {\n if (platform !== 'linux') return { libc: null, version: null };\n try {\n const report = process.report?.getReport();\n if (typeof report !== 'object' || report === null) return { libc: null, version: null };\n const header = (report as { header?: { glibcVersionRuntime?: string } }).header;\n const version = header?.glibcVersionRuntime ?? null;\n return { libc: version ? 'glibc' : 'musl', version };\n } catch {\n // Unknown libc must not select a potentially incompatible GNU executable.\n return { libc: null, version: null };\n }\n}\n\n/** Optional inputs let discovery be tested without executing a compiler or mutating process globals. */\nexport interface EngineDiscovery {\n readonly roots?: readonly string[];\n readonly env?: NodeJS.ProcessEnv;\n readonly platform?: string;\n readonly arch?: string;\n readonly libc?: Libc;\n readonly glibcVersion?: string | null;\n readonly resolvePackage?: (specifier: string) => string;\n}\n\nconst requireFromHere = createRequire(import.meta.url);\n\nfunction packageRoots(): string[] {\n const here = dirname(fileURLToPath(import.meta.url));\n const roots = [resolve(here, '..', '..')];\n try {\n roots.unshift(dirname(requireFromHere.resolve('@noego/trust/package.json')));\n } catch {\n // A checkout run from src/ can use its relative root.\n }\n return [...new Set(roots)];\n}\n\nfunction isFile(path: string, executable = false, platform = process.platform as string): boolean {\n try {\n if (!statSync(path).isFile()) return false;\n accessSync(path, executable && platform !== 'win32' ? constants.X_OK : constants.R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction packageVersion(roots: readonly string[], name: string): string | null {\n for (const root of roots) {\n try {\n const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; optionalDependencies?: Record<string, string> };\n const version = manifest.optionalDependencies?.[name];\n if (manifest.name === '@noego/trust' && typeof version === 'string' && /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) return version;\n } catch {\n // Try the next root.\n }\n }\n return null;\n}\n\n/** Explicit override, exact-version platform package, then a local development build. */\nexport function nativeBinary(options: EngineDiscovery = {}): string | null {\n const env = options.env ?? process.env;\n if (env.TRUST_NATIVE_BIN) return env.TRUST_NATIVE_BIN;\n const roots = options.roots ?? packageRoots();\n const platform = options.platform ?? process.platform;\n const linux = runtimeLinux(platform);\n const libc = options.libc === undefined ? linux.libc : options.libc;\n const glibcVersion = options.glibcVersion === undefined ? linux.version : options.glibcVersion;\n const supported = platform !== 'linux' || (libc === 'glibc' && supportsNativeGlibc(glibcVersion));\n const name = supported ? nativePlatformPackage(platform, options.arch ?? process.arch, libc) : null;\n const version = name ? packageVersion(roots, name) : null;\n const executable = platform === 'win32' ? 'trust-native.exe' : 'trust-native';\n if (name && version) {\n try {\n const manifestPath = (options.resolvePackage ?? requireFromHere.resolve)(`${name}/package.json`);\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { name?: string; version?: string };\n const candidate = join(dirname(manifestPath), 'bin', executable);\n // A stale or manually hoisted optional package must never run a different engine version.\n if (manifest.name === name && manifest.version === version && isFile(candidate, true, platform)) return candidate;\n } catch {\n // Optional dependencies may be omitted, unsupported, or unavailable. Wasm remains usable.\n }\n }\n return roots.map((root) => join(root, 'native', 'target', 'release', executable))\n .find((candidate) => isFile(candidate, true, platform)) ?? null;\n}\n\n/** Explicit override, packaged Wasm, then a local development build. */\nexport function nativeWasm(options: EngineDiscovery = {}): string | null {\n const env = options.env ?? process.env;\n if (env.TRUST_NATIVE_WASM) return env.TRUST_NATIVE_WASM;\n const candidates = (options.roots ?? packageRoots()).flatMap((root) => [\n join(root, 'dist', 'native', 'trust_native_wasm.wasm'),\n join(root, 'native', 'target', 'wasm32-wasip1', 'wasm', 'trust_native_wasm.wasm'),\n join(root, 'native', 'target', 'wasm32-wasip1', 'release', 'trust_native_wasm.wasm'),\n ]);\n return candidates.find((candidate) => isFile(candidate)) ?? null;\n}\n\n/** Native is preferred; the bundled Wasm works even with npm --omit=optional. */\nexport function nativeEngine(options: EngineDiscovery = {}): NativeEngine | null {\n const forced = (options.env ?? process.env).TRUST_NATIVE_ENGINE;\n if (forced !== 'wasm') {\n const path = nativeBinary(options);\n if (path) return { kind: 'binary', path };\n if (forced === 'binary') return null;\n }\n const path = nativeWasm(options);\n return path ? { kind: 'wasm', path } : null;\n}\n","// Native trust check. TypeScript is a build-time engine input, not a runtime dependency.\nimport { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { emptyTrustConfig } from '../core/check-file.js';\nimport { compareFindings, formatFinding } from '../core/report.js';\nimport { loadTrustConfig } from '../eslint/config.js';\nimport { groupMatches, realpathOrSelf, Zones } from '../eslint/zones.js';\nimport { checkNative } from './native-check.js';\nimport { formatWalkFailure, resolveFiles } from './source-files.js';\n\nexport interface CheckCommandOptions {\n readonly cwd: string;\n readonly paths: readonly string[];\n readonly configFile: string;\n readonly strict: boolean;\n readonly tsconfig?: string;\n readonly root?: string;\n readonly perf?: boolean;\n readonly json?: boolean;\n readonly log: (line: string) => void;\n}\n\n/** 0 clean/warnings only; 1 trust errors; 2 usage, configuration, syntax, or engine failure. */\nexport async function runCheckCommand(options: CheckCommandOptions): Promise<number> {\n const fail = (errors: readonly string[]): number => {\n if (options.json) options.log(JSON.stringify({ findings: [], errors, warnings: [] }));\n else for (const error of errors) options.log(error);\n return 2;\n };\n if (options.paths.length === 0) return fail(['trust check needs at least one path: trust check <paths...> [--strict] [--perf] [--json]']);\n try {\n const resolved = resolveFiles(options.cwd, options.paths);\n if ('missing' in resolved) return fail([`trust check: no such file or directory: ${resolved.missing}`]);\n const configPath = resolve(options.cwd, options.configFile);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = existsSync(configPath) ? loadTrustConfig(configPath, { rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);\n const warnings = config.unmatchedGlobs.map(line => `trust check: warning: ${line}`);\n const zones = new Zones(config.rootDir, config.passthrough, config.ignore);\n const files = resolved.files.filter(file => zones.zoneOf(file) !== 'ignore');\n const skipped = resolved.files.length - files.length;\n const strictByConfig = files.filter(file => config.strict.some(group => groupMatches(group, realpathOrSelf(file))));\n const result = await checkNative({\n cwd: options.cwd, files, config, programs: { tsconfig: options.tsconfig, mappings: config.tsconfig },\n strictFiles: options.strict ? files : strictByConfig, perf: options.perf,\n // Keep --json a single parseable document, even with debugging enabled.\n log: line => { if (!options.json) options.log(line); },\n });\n if (result.walk.status !== 'ok') return fail(formatWalkFailure('trust check', result.walk));\n const findings = result.findings.sort(compareFindings).map(finding => ({ ...finding, severity: finding.severity ?? 'error' }));\n const errors = findings.filter(finding => finding.severity === 'error').length;\n const advice = findings.length - errors;\n if (options.json) {\n options.log(JSON.stringify({ findings, errors: [], warnings, summary: { errors, warnings: advice, checkedFiles: files.length, skippedFiles: skipped } }));\n } else {\n for (const warning of warnings) options.log(warning);\n for (const finding of findings) options.log(formatFinding(finding));\n const notes: string[] = [];\n if (options.strict) notes.push('strict');\n else if (strictByConfig.length) notes.push(`${strictByConfig.length} strict by config`);\n if (options.perf) notes.push('perf');\n const counts = options.perf ? `${errors} error(s), ${advice} warning(s)` : `${findings.length} finding(s)`;\n options.log(`${counts} in ${files.length} checked file(s), ${skipped} ignored file(s) skipped${notes.length ? ` (${notes.join(', ')})` : ''}.`);\n }\n return errors > 0 ? 1 : 0;\n } catch (error) {\n return fail([`trust check: ${error instanceof Error ? error.message : String(error)}`]);\n }\n}\n","// One heavy Trust run per machine. `trust baseline`, `check` and `refactor` each hold a whole\n// TypeScript program (several GB on a large repo); agents in parallel worktrees used to start\n// many at once and push the machine into swap.\n//\n// Like sqlego's owner socket, the lock is a listening Unix socket (a named pipe on Windows), not\n// a pid file: the kernel closes it when the holder exits or is killed, so it cannot be left\n// stuck and pid reuse cannot fake a live holder. A run that finds it held stays connected and\n// wakes the moment the holder's socket closes. A socket file left by a crash refuses\n// connections and is removed; that removal is serialized through a short-lived `reclaim.lock`\n// whose age, not a pid, decides when it is stale.\n//\n// TRUST_RUNTIME_DIR moves the lock directory (default `<tmpdir>/noego-trust`).\n// TRUST_RUN_LOCK=0 skips the lock (e.g. a caller that already serializes runs).\nimport { closeSync, mkdirSync, openSync, rmSync, statSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { createConnection, createServer, type Server, type Socket } from 'node:net';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface RunLockOptions {\n readonly directory?: string;\n /** Called once, when the run first has to wait. */\n readonly onWait?: () => void;\n /** Age after which a leftover reclaim.lock is ignored (default 10 s). */\n readonly reclaimStaleMs?: number;\n}\n\nexport interface RunLock {\n readonly path: string;\n release(): Promise<void>;\n}\n\nexport function runLockDirectory(env: NodeJS.ProcessEnv = process.env): string {\n return env.TRUST_RUNTIME_DIR || join(tmpdir(), 'noego-trust');\n}\n\nexport function runLockDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.TRUST_RUN_LOCK === '0';\n}\n\nexport function runLockSocketPath(directory: string, platform: NodeJS.Platform = process.platform): string {\n if (platform !== 'win32') return join(directory, 'run.sock');\n const hash = createHash('sha256').update(directory).digest('hex').slice(0, 16);\n return `\\\\\\\\.\\\\pipe\\\\noego-trust-${hash}-run`;\n}\n\nfunction errnoCode(error: unknown): string | undefined {\n return (error as NodeJS.ErrnoException | undefined)?.code;\n}\n\ntype Listen = { readonly kind: 'held'; readonly server: Server } | { readonly kind: 'in-use' };\n\nfunction listen(socketPath: string): Promise<Listen> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n // EEXIST: on macOS, a bind racing another waiter's bind on the same path after a release.\n server.once('error', (error) => {\n const code = errnoCode(error);\n if (code === 'EADDRINUSE' || code === 'EEXIST') resolve({ kind: 'in-use' });\n else reject(error);\n });\n server.listen(socketPath, () => resolve({ kind: 'held', server }));\n });\n}\n\ntype Probe = { readonly kind: 'alive'; readonly socket: Socket } | { readonly kind: 'dead' };\n\nfunction probe(socketPath: string): Promise<Probe> {\n return new Promise((resolve, reject) => {\n const socket = createConnection(socketPath);\n socket.once('connect', () => resolve({ kind: 'alive', socket }));\n socket.once('error', (error) => {\n const code = errnoCode(error);\n // Refused: a crashed holder's socket file. ENOTSOCK: something else left at the path.\n if (code === 'ECONNREFUSED' || code === 'ENOENT' || code === 'ENOTSOCK') resolve({ kind: 'dead' });\n else reject(error);\n });\n });\n}\n\nfunction waitForClose(socket: Socket): Promise<void> {\n return new Promise((resolve) => {\n socket.once('close', () => resolve());\n socket.on('error', () => undefined); // ECONNRESET when the holder dies: 'close' follows.\n socket.on('data', () => undefined);\n });\n}\n\n/** Removes a dead holder's socket file, one reclaimer at a time; false when another is reclaiming. */\nfunction reclaim(directory: string, socketPath: string, staleMs: number): boolean {\n const guard = join(directory, 'reclaim.lock');\n try {\n closeSync(openSync(guard, 'wx'));\n } catch (error) {\n if (errnoCode(error) !== 'EEXIST') throw error;\n try {\n if (Date.now() - statSync(guard).mtimeMs < staleMs) return false;\n } catch {\n return false; // It vanished: the other reclaimer finished.\n }\n rmSync(guard, { force: true });\n return false;\n }\n try {\n rmSync(socketPath, { force: true });\n } finally {\n rmSync(guard, { force: true });\n }\n return true;\n}\n\n/** Waits until this process holds the machine-wide Trust run lock. */\nexport async function acquireRunLock(options: RunLockOptions = {}): Promise<RunLock> {\n const directory = options.directory ?? runLockDirectory();\n const reclaimStaleMs = options.reclaimStaleMs ?? 10_000;\n mkdirSync(directory, { recursive: true });\n const socketPath = runLockSocketPath(directory);\n let announced = false;\n for (;;) {\n const listened = await listen(socketPath);\n if (listened.kind === 'held') return holdLock(listened.server, socketPath);\n const probed = await probe(socketPath);\n if (probed.kind === 'dead') {\n if (!reclaim(directory, socketPath, reclaimStaleMs)) await new Promise((done) => setTimeout(done, 50));\n continue;\n }\n if (!announced) {\n announced = true;\n options.onWait?.();\n }\n await waitForClose(probed.socket);\n }\n}\n\nfunction holdLock(server: Server, socketPath: string): RunLock {\n const waiters = new Set<Socket>();\n server.on('connection', (socket) => {\n waiters.add(socket);\n socket.on('error', () => undefined);\n socket.once('close', () => waiters.delete(socket));\n });\n server.unref();\n let released: Promise<void> | undefined;\n const release = () => {\n released ??= new Promise<void>((resolve) => {\n // Closing the server removes the Unix socket file; destroying the connections wakes every waiter.\n server.close(() => resolve());\n for (const socket of waiters) socket.destroy();\n });\n return released;\n };\n return { path: socketPath, release };\n}\n","// `trust explain <file>:<line>[:<column>]` — which origin does each call on that line resolve to,\n// and why is it (un)trusted, both for failing (`trust`) and for its types (`trust_type`)? Tells the user\n// exactly which entry to add or remove. A call to a type guard or assertion function also says what it\n// narrows and whether the origin declaring it is type-trusted (`untrusted-value`'s `guard` entry). Also\n// lists every type claim that starts on the line (`type-claim`): its kind and why it is a claim; and every\n// untrusted value that starts on it (`untrusted-value`): how it entered, the origin that declared its type,\n// and whether its use is reported. Claims and values are listed only when the config turns their rule on,\n// as `trust check` reports them. A failure-path finding on the line that `//trust:accept <reason>` accepts\n// is listed with its reason. In a boundary file (`boundaries`), every boundary starting on the line is listed:\n// the item it belongs to, whether an `exclude` entry leaves it out, and what its return value says.\nimport { svelteFor, svelteForSource } from '../core/svelte.js';\nimport { resolve } from 'node:path';\nimport type * as TS from 'typescript';\nimport { boundaryContext, boundaryName, excludeMatches, fileBoundaries, itemLabel, type BoundaryVerdict } from '../core/boundaries.js';\nimport { checkSourceFileWithAccepted, isStrictByConfig, positionAt, startOf } from '../core/check-file.js';\nimport { ANY_KIND } from '../core/dropped-results.js';\nimport { BOUNDARY_RULE, formatFailureKinds, TYPE_CLAIM_RULE, UNTRUSTED_ENTRY_LABELS, UNTRUSTED_VALUE_RULE, type TypeClaimOrigin, type UntrustedEntry } from '../core/messages.js';\nimport { createPrograms, sourceFileOf, type MissingMappedTsconfig } from '../core/program.js';\nimport { claimSpan, typeClaimContext, typeClaimMessage, typeClaimsIn } from '../core/type-claims.js';\nimport {\n callTypeVerdict,\n guardCallOf,\n untrustedValueContext,\n untrustedValueMessage,\n untrustedValuesIn,\n type CallTypeVerdict,\n type GuardVerdict,\n type UntrustedOutcome,\n type UntrustedValueContext,\n} from '../core/untrusted-values.js';\nimport { isRuleEnabled, loadTrustConfig, type OptInRule } from '../eslint/config.js';\nimport { TrustPolicy, type Verdict } from '../eslint/policy.js';\nimport { loadTypeScript } from '../eslint/typescript.js';\n\nexport interface ExplainOptions {\n readonly cwd: string;\n readonly file: string;\n readonly line: number;\n readonly column?: number;\n readonly configFile: string;\n readonly tsconfig?: string;\n /** Directory the config's paths resolve against, instead of the config file's directory. */\n readonly root?: string;\n}\n\nexport interface ExplainedCall {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n /** Throw trust: may the call fail (`trust` / `distrust`)? */\n readonly verdict: Verdict;\n /** Type trust: is what the call returns what its type says (`trust_type` / `distrust_type`)? */\n readonly typeTrust: CallTypeVerdict;\n /** When the callee is a type guard or assertion function: what it narrows, and who vouches for that. */\n readonly guard: ExplainedGuard | null;\n readonly declaredAt: string | null;\n}\n\n/** A call to a type guard (`x is T`) or assertion function (`asserts x is T`): `untrusted-value`'s `guard` entry. */\nexport interface ExplainedGuard {\n /** The signature's predicate, as the call instantiates it (`data is User`). */\n readonly predicate: string;\n /** The value it narrows, as written at the call. */\n readonly narrows: string;\n readonly asserts: boolean;\n /** Type trust of the origin that declares the signature: `type-untrusted` makes the narrowed value untrusted. */\n readonly verdict: GuardVerdict;\n}\n\n/** One type claim starting at the location: what `trust check` reports there under `type-claim`. */\nexport interface ExplainedClaim {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n /** The claim kind (`claim:as`, `claim:non-null`, …), `unanalyzable`, or `directive` (a `//trust:` comment that marks nothing): the finding's origin and baseline key. */\n readonly origin: TypeClaimOrigin;\n /** Why it is a claim: the finding's message. */\n readonly why: string;\n}\n\n/** One untrusted value starting at the location: what `untrusted-value` decides there. */\nexport interface ExplainedValue {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n /** How the value entered checked code. */\n readonly entry: UntrustedEntry;\n /** The origin that declared its type: the finding's origin and baseline key, and the `trust_type` entry that would trust it. */\n readonly origin: string;\n /** The type it is declared to have. */\n readonly type: string;\n /** `finding` when `trust check` reports its use here. */\n readonly outcome: UntrustedOutcome;\n /** The finding's message, or why nothing is reported. */\n readonly why: string;\n}\n\n/** One failure-path finding starting at the location that a `//trust:accept` accepted: `trust check` does not report it. */\nexport interface ExplainedAcceptance {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n readonly rule: string;\n readonly origin: string;\n /** The finding's message: what would be reported without the directive. */\n readonly why: string;\n /** The reason written after `//trust:accept`. */\n readonly reason: string;\n /** 1-based line of the directive. */\n readonly directiveLine: number;\n}\n\n/** One boundary (exported function or public member of a boundary file) starting at the location. */\nexport interface ExplainedBoundary {\n readonly line: number;\n readonly column: number;\n /** `Class.member` or `fn`: the name an `exclude` entry uses. */\n readonly member: string;\n /** The `boundaries` item the file belongs to (`boundaries[0] in trust.config.json`). */\n readonly item: string;\n /** The `exclude` entry that leaves it out, or null. */\n readonly excludedBy: string | null;\n /** What its return value says: plain data, a Result that can fail, or `any` / `unknown`. */\n readonly verdict: BoundaryVerdict;\n /** Whether `trust check` reports it (not excluded, and not plain data), and as what. */\n readonly reported: 'error' | 'warning' | null;\n}\n\nexport interface Explanation {\n readonly file: string;\n readonly zone: string;\n readonly calls: readonly ExplainedCall[];\n readonly claims: readonly ExplainedClaim[];\n readonly values: readonly ExplainedValue[];\n readonly accepted: readonly ExplainedAcceptance[];\n readonly boundaries: readonly ExplainedBoundary[];\n /** Opt-in rules the config leaves off: their claims / values are not listed (nor reported by `trust check`). */\n readonly off: readonly OptInRule[];\n}\n\nfunction clipText(raw: string): string {\n const text = raw.replace(/\\s+/g, ' ');\n return text.length > 80 ? `${text.slice(0, 77)}...` : text;\n}\n\nfunction declaredAt(ts: typeof TS, policy: TrustPolicy, node: TS.CallExpression | TS.NewExpression): string | null {\n const resolved = policy.calleeDeclaration(node);\n if (!resolved) return null;\n const source = resolved.declaration.getSourceFile();\n const { line } = ts.getLineAndCharacterOfPosition(source, resolved.declaration.getStart(source));\n const inputs = svelteForSource(source);\n const original = inputs?.position(source.fileName, startOf(ts, source, resolved.declaration));\n return `${inputs?.original(source.fileName) ?? source.fileName}:${original?.line ?? line + 1}`;\n}\n\nfunction explainGuard(call: TS.CallExpression, source: TS.SourceFile, context: UntrustedValueContext): ExplainedGuard | null {\n const guard = guardCallOf(call, context);\n return guard ? { predicate: guard.predicate, narrows: clipText(guard.argument.getText(source)), asserts: guard.asserts, verdict: guard.verdict } : null;\n}\n\nconst NOT_REPORTED: Readonly<Record<Exclude<UntrustedOutcome, 'finding'>, string>> = {\n allowed: 'not reported: it is passed to a validator, kept as `unknown`, tested by a built-in check, or kept in a variable with no written type',\n 'no-claim': 'not reported: its type claims nothing (`unknown`, `any`, an empty type or a function)',\n validator: 'not reported: it is inside a validator',\n};\n\nexport type ExplainResult = { readonly kind: 'explained'; readonly explanation: Explanation } | MissingMappedTsconfig;\n\n/** The file compiles under `--tsconfig`, else the config's matching `tsconfig` entry, else the nearest tsconfig.json. */\nexport function explain(options: ExplainOptions): ExplainResult {\n const ts = loadTypeScript(options.cwd);\n const file = resolve(options.cwd, options.file);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = loadTrustConfig(resolve(options.cwd, options.configFile), { rootDir });\n const creation = createPrograms(ts, options.cwd, [file], options.tsconfig, config.tsconfig);\n if (creation.kind !== 'created') return creation;\n const [{ program }] = creation.groups;\n const source = sourceFileOf(program, file);\n if (!source) throw new Error(`could not load ${file} into a TypeScript program`);\n const checker = program.getTypeChecker();\n const policy = new TrustPolicy(ts, checker, config);\n const valueContext = untrustedValueContext(ts, checker, policy);\n const generatedLines = svelteFor(checker)?.generatedLines(source.fileName, options.line);\n const here = (position: { line: number; column: number }): { line: number; column: number } | null => {\n if (generatedLines && !generatedLines.has(position.line)) return null;\n const mapped = svelteFor(checker)?.position(source.fileName, position);\n if (mapped === null) return null;\n position = mapped ?? position;\n const onLine = position.line === options.line;\n return onLine && (options.column === undefined || position.column === options.column) ? position : null;\n };\n const calls: ExplainedCall[] = [];\n const visit = (node: TS.Node): void => {\n if (ts.isCallExpression(node) || ts.isNewExpression(node)) {\n const position = here(startOf(ts, source, node));\n if (position) {\n calls.push({\n ...position,\n text: clipText(node.getText(source)),\n verdict: (() => {\n const verdict = policy.classify(node);\n const wrapper = policy.lookup('svelte.__renderSnippet', 'svelte');\n return verdict.kind === 'untrusted' && !verdict.distrustedBy && verdict.origin.origin === 'svelte.Snippet'\n && svelteFor(checker)?.snippetCall(source.fileName, node.getStart(source)) && wrapper.trusted\n ? { kind: 'trusted' as const, origin: verdict.origin, by: wrapper.by } : verdict;\n })(),\n typeTrust: callTypeVerdict(node, valueContext),\n guard: ts.isCallExpression(node) ? explainGuard(node, source, valueContext) : null,\n declaredAt: declaredAt(ts, policy, node),\n });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n // The same decisions `trust check` reports under `type-claim`, with the finding's message as the reason\n // (a directive finding is reported at its comment, so its text is the comment).\n const claimsOn = isRuleEnabled(config, TYPE_CLAIM_RULE);\n const valuesOn = isRuleEnabled(config, UNTRUSTED_VALUE_RULE);\n // Only the rules explain lists items for; dropped-result findings are explained by their message.\n const explained: readonly OptInRule[] = [TYPE_CLAIM_RULE, UNTRUSTED_VALUE_RULE];\n const off = explained.filter((rule) => !isRuleEnabled(config, rule));\n const claims = (claimsOn ? typeClaimsIn(source, typeClaimContext(ts, checker, undefined, policy)) : []).flatMap((claim): ExplainedClaim[] => {\n const span = claimSpan(claim, source);\n const position = here(positionAt(ts, source, span.start));\n return position ? [{ ...position, text: clipText(source.text.slice(span.start, span.end)), origin: claim.origin, why: typeClaimMessage(claim) }] : [];\n });\n // The same decisions `trust check` reports under `untrusted-value`, and the untrusted values it lets pass.\n // Left out, because another block already explains them: a value a member is read from when that member\n // is itself an untrusted value (`process.env` in `process.env.HOME`: the member read is the one explained),\n // and a call whose result claims nothing (`void`, `unknown`, `any`: its call block has the type-trust verdict).\n const found = valuesOn ? untrustedValuesIn(source, valueContext) : [];\n const valueNodes = new Set<TS.Node>(found.map((value) => value.node));\n const isReadThrough = (node: TS.Node): boolean =>\n (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node && valueNodes.has(node.parent);\n const isCall = (node: TS.Node): boolean => ts.isCallExpression(node) || ts.isNewExpression(node);\n const values = found.flatMap((value): ExplainedValue[] => {\n const position = here(startOf(ts, source, value.node));\n if (!position || isReadThrough(value.node) || (value.outcome === 'no-claim' && isCall(value.node))) return [];\n const why = value.outcome === 'finding' ? untrustedValueMessage(value) : NOT_REPORTED[value.outcome];\n return [{ ...position, text: clipText(value.node.getText(source)), entry: value.entry, origin: value.origin, type: value.type, outcome: value.outcome, why }];\n });\n // The failure-path findings `trust check` would report here but a `//trust:accept` accepts, with its reason.\n const accepted = checkSourceFileWithAccepted({ ts, program, checker, config, sourceFile: source }).accepted.flatMap((entry): ExplainedAcceptance[] => {\n const { finding, acceptance } = entry;\n const position = here({ line: finding.line, column: finding.column });\n if (!position) return [];\n const directivePosition = positionAt(ts, source, acceptance.directive.pos);\n const directiveLine = svelteFor(checker)?.position(source.fileName, directivePosition)?.line ?? directivePosition.line;\n return [{ ...position, text: clipText(entry.text), rule: finding.rule, origin: finding.origin, why: finding.message, reason: acceptance.reason, directiveLine }];\n });\n // The boundaries of a boundary file (`boundaries` in the config) that start on the line, as boundary-result sees them.\n const boundaries: ExplainedBoundary[] = [];\n if (config.boundaries.length > 0) {\n const found = fileBoundaries(source, boundaryContext(ts, checker, program, policy, config));\n if (found.kind === 'boundary') {\n const strict = isStrictByConfig(config, source.fileName);\n for (const boundary of found.boundaries) {\n const position = here(positionAt(ts, source, boundary.start));\n if (!position) continue;\n const excludedBy = found.item.exclude.find((entry) => excludeMatches(entry, boundary)) ?? null;\n const reported = excludedBy || boundary.verdict.kind === 'plain' ? null : boundary.verdict.kind === 'result' || strict ? 'error' : 'warning';\n boundaries.push({ ...position, member: boundaryName(boundary), item: itemLabel(found.item), excludedBy, verdict: boundary.verdict, reported });\n }\n }\n }\n const unique = <T>(items: T[]): T[] => [...new Map(items.map(item => [JSON.stringify(item), item])).values()];\n return {\n kind: 'explained',\n explanation: { file, zone: policy.zones.zoneOf(file), calls: unique(calls), claims: unique(claims), values: unique(values), accepted: unique(accepted), boundaries: unique(boundaries), off },\n };\n}\n\n/** The lines of one boundary: the item, the exclusion, and what the return value says. */\nfunction describeBoundary(boundary: ExplainedBoundary): string[] {\n const lines = [` boundary: ${boundary.member} (${boundary.item}, rule ${BOUNDARY_RULE})`];\n const { verdict } = boundary;\n const returns =\n verdict.kind === 'plain'\n ? 'plain data: nothing reported'\n : verdict.kind === 'result'\n ? verdict.kinds.length === 0\n ? 'a Result object that cannot fail'\n : `a Result that can fail with ${formatFailureKinds(verdict.kinds, ANY_KIND)}`\n : `\\`${verdict.type}\\`, which may hold a Result`;\n if (boundary.excludedBy) lines.push(` returns: ${returns}`, ` excluded: by \"${boundary.excludedBy}\" in the item's \"exclude\": nothing reported`);\n else if (boundary.reported) lines.push(` returns: ${returns}: reported as ${boundary.reported === 'warning' ? 'a warning (an error where strict applies)' : 'an error'}`);\n else lines.push(` returns: ${returns}`);\n return lines;\n}\n\nfunction describe(verdict: Verdict): string[] {\n switch (verdict.kind) {\n case 'unresolved':\n return ['verdict: not checked (callee has no declaration, e.g. an `any` value)'];\n case 'first-party':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (first-party code in a checked file is checked itself)'];\n case 'returns-result':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (declared return type is Result from @noego/trust)'];\n case 'trusted':\n return [`origin: ${verdict.origin.origin}`, `verdict: trusted by \"${verdict.by.entry}\" in ${verdict.by.source}`];\n case 'calls-ignored':\n return [\n `origin: ${verdict.origin.origin}`,\n 'verdict: reported (callsIgnored): the callee file is ignored; make it passthrough so calls into it must be handled',\n ];\n case 'untrusted':\n return [\n `origin: ${verdict.origin.origin}`,\n verdict.distrustedBy\n ? `verdict: UNTRUSTED (distrusted by \"${verdict.distrustedBy.entry}\" in ${verdict.distrustedBy.source})`\n : 'verdict: UNTRUSTED (no trust entry matches)',\n `hint: guard it, or trust \"${verdict.origin.origin}\" (or a prefix of it) in trust.config.json`,\n ];\n }\n}\n\n/** The type-trust lines of a call: is what it returns what its type says? */\nfunction describeTypeTrust(verdict: CallTypeVerdict): string[] {\n switch (verdict.kind) {\n case 'unresolved':\n return [];\n case 'first-party':\n return ['types: trusted (first-party code in a checked file is checked itself)'];\n case 'trust-package':\n return ['types: trusted (declared by @noego/trust)'];\n case 'validator':\n return ['types: trusted (the callee is a validator: //trust:validator_function)'];\n case 'type-trusted':\n return [`types: type-trusted by \"${verdict.by.entry}\" in ${verdict.by.source}`];\n case 'caller-chosen-generic':\n return [\n 'types: UNTRUSTED (the call picks its own return type: a type parameter found only in the return position, which no type trust proves)',\n ' validate the returned value',\n ];\n case 'type-untrusted':\n return [\n verdict.distrustedBy\n ? `types: UNTRUSTED (type-distrusted by \"${verdict.distrustedBy.entry}\" in ${verdict.distrustedBy.source})`\n : 'types: UNTRUSTED (no trust_type entry matches)',\n ` validate what it returns, or add \"${verdict.origin.origin}\" (or a prefix of it) to \"trust_type\" in trust.config.json`,\n ];\n }\n}\n\n/** The guard lines of a call to a type guard or assertion function: is what it narrows what its predicate says? */\nfunction describeGuard(guard: ExplainedGuard): string[] {\n const head = `guard: ${guard.asserts ? 'asserts' : 'narrows'} \"${guard.narrows}\" (${guard.predicate}), declared by \"${guard.verdict.origin.origin}\"`;\n switch (guard.verdict.kind) {\n case 'first-party':\n return [head, ' not an untrusted value: first-party code in a checked file (its written predicate is a type claim, rule type-claim)'];\n case 'trust-package':\n return [head, ' trusted (declared by @noego/trust)'];\n case 'validator':\n return [head, ' trusted (the guard is a validator: //trust:validator_function)'];\n case 'built-in':\n return [head, ' trusted (a built-in check)'];\n case 'type-trusted':\n return [head, ` type-trusted by \"${guard.verdict.by.entry}\" in ${guard.verdict.by.source}`];\n case 'type-untrusted':\n return [\n head,\n guard.verdict.distrustedBy\n ? ` UNTRUSTED (type-distrusted by \"${guard.verdict.distrustedBy.entry}\" in ${guard.verdict.distrustedBy.source}): the narrowed value is untrusted (rule ${UNTRUSTED_VALUE_RULE})`\n : ` UNTRUSTED (no trust_type entry matches): the narrowed value is untrusted (rule ${UNTRUSTED_VALUE_RULE})`,\n ` validate the value instead, or add \"${guard.verdict.origin.origin}\" (or a prefix of it) to \"trust_type\" in trust.config.json`,\n ];\n }\n}\n\nexport function formatExplanation(explanation: Explanation): string {\n const lines = [`${explanation.file} (zone: ${explanation.zone})`];\n if (explanation.zone !== 'checked') {\n lines.push('note: calls, type claims and untrusted values in this file are not checked (only checked-zone files are linted)');\n }\n for (const rule of explanation.off) {\n lines.push(`note: ${rule} is off in this config, so it is not explained; turn it on with \"rules\": { \"${rule}\": \"on\" } in trust.config.json`);\n }\n if (explanation.calls.length === 0 && explanation.claims.length === 0 && explanation.values.length === 0 && explanation.accepted.length === 0 && explanation.boundaries.length === 0) {\n lines.push('no call, `new` expression, type claim, untrusted value or boundary starts at that location');\n }\n for (const boundary of explanation.boundaries) {\n lines.push('', `${boundary.line}:${boundary.column} ${boundary.member}`);\n lines.push(...describeBoundary(boundary));\n }\n for (const accepted of explanation.accepted) {\n lines.push('', `${accepted.line}:${accepted.column} ${accepted.text}`);\n lines.push(` accepted: ${accepted.rule} (${accepted.origin}) by //trust:accept on line ${accepted.directiveLine}`);\n lines.push(` reason: ${accepted.reason}`);\n lines.push(` finding: ${accepted.why}`);\n }\n for (const call of explanation.calls) {\n lines.push('', `${call.line}:${call.column} ${call.text}`);\n for (const detail of describe(call.verdict)) lines.push(` ${detail}`);\n for (const detail of describeTypeTrust(call.typeTrust)) lines.push(` ${detail}`);\n if (call.guard) for (const detail of describeGuard(call.guard)) lines.push(` ${detail}`);\n if (call.declaredAt) lines.push(` declared: ${call.declaredAt}`);\n }\n for (const claim of explanation.claims) {\n lines.push('', `${claim.line}:${claim.column} ${claim.text}`);\n lines.push(` claim: ${claim.origin} (rule ${TYPE_CLAIM_RULE})`);\n lines.push(` why: ${claim.why}`);\n }\n for (const value of explanation.values) {\n lines.push('', `${value.line}:${value.column} ${value.text}`);\n lines.push(` value: untrusted \"${value.type}\", ${UNTRUSTED_ENTRY_LABELS[value.entry]} \"${value.origin}\" (rule ${UNTRUSTED_VALUE_RULE})`);\n lines.push(` use: ${value.why}`);\n }\n return lines.join('\\n');\n}\n","// `trust refactor [paths…] [--baseline <path>] [--json] [--value-only] [--max-group <n>] [--tsconfig <path>] [--root <dir>]`\n// — the order to refactor a tree in. A file's inferred failure and return types change when the files\n// it imports change, so the work starts at the leaves. The command builds the static import graph of\n// the files `trust baseline` would check (same file walk, programs, tsconfig mapping and ignore zone),\n// collapses circular imports into groups, layers the result into waves, and keeps only the files that\n// have findings: the ones in trust-baseline.json, or those of a fresh check when there is no baseline.\n//\n// A circular group above the size threshold is too large for one unit of work. It is shrunk in steps,\n// and nothing above the threshold leaves without saying so:\n// 1. the imports inside it that cannot carry a change (an interface, a constant, a frozen Result\n// contract: core/change.ts) are left out, and what is left is planned again;\n// 2. a group still too large gets an internal order: its declarations with findings, callees first,\n// from the calls between its declarations (core/call-graph.ts);\n// 3. declarations that call each other in a circle are reported with the calls that close the circle\n// and the two ways out (freeze a contract, or iterate to a fixed point).\n// Every circular group, of any size, lists the imports that close it (optional structural cleanup).\n// Runs on TypeScript alone (no ESLint).\nimport { svelteFor } from '../core/svelte.js';\nimport { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type * as TS from 'typescript';\nimport { collectCalls, declarationAt } from '../core/call-graph.js';\nimport { changeOracleFor } from '../core/change.js';\nimport { checkSourceFile, emptyTrustConfig, policyFor } from '../core/check-file.js';\nimport { collectImports } from '../core/import-graph.js';\nimport { planRefactor, type CircularGroup, type PlanEdge, type WorkItem } from '../core/refactor-plan.js';\nimport { loadTrustConfig, type TrustConfig } from '../eslint/config.js';\nimport type { TypeScript } from '../eslint/typescript.js';\nimport { realpathOrSelf, Zones } from '../eslint/zones.js';\nimport { readBaseline } from './baseline-command.js';\nimport { forEachSourceFile, logUnmatchedGlobs, logWalkFailure, relativeTo, resolveFiles } from './source-files.js';\n\n/** A circular group with more files than this is reported as too large for one unit of work. */\nexport const DEFAULT_MAX_GROUP_SIZE = 8;\n\n/** Cutting an import costs this much per imported name that can change, and 1 per name that cannot. */\nconst CHANGING_NAME_COST = 10;\n\nexport interface RefactorCommandOptions {\n readonly cwd: string;\n /** Files or directories; the current directory when empty. */\n readonly paths: readonly string[];\n readonly configFile: string;\n /** Where the tasks come from; `<root>/trust-baseline.json` when omitted, a fresh check when that does not exist. */\n readonly baselineFile?: string;\n /** Print the plan as JSON instead of text. */\n readonly json: boolean;\n /** Leave type-only imports out of the graph. */\n readonly valueOnly: boolean;\n /** Defaults to DEFAULT_MAX_GROUP_SIZE. */\n readonly maxGroupSize?: number;\n /** One tsconfig for every file, instead of the config's `tsconfig` entries or the nearest tsconfig.json. */\n readonly tsconfig?: string;\n /** Directory the config's paths resolve against, instead of the config file's directory. */\n readonly root?: string;\n readonly log: (line: string) => void;\n}\n\n/** An `import(...)` whose specifier is computed: the graph has no edge for it. */\nexport interface ComputedImportWarning {\n readonly kind: 'computed-import';\n readonly file: string;\n readonly line: number;\n readonly column: number;\n readonly specifier: string;\n}\n\n/** An import that closes a circular group: `from` imports `names` from `to` (`*` is the module as a whole). */\nexport interface ClosingImport {\n readonly from: string;\n readonly to: string;\n readonly names: readonly string[];\n}\n\n/** A call that closes a recursion: the declaration `from` calls the declaration `to` at `callSites` places. */\nexport interface ClosingCall {\n readonly from: string;\n readonly to: string;\n readonly callSites: number;\n}\n\n/** Declarations that call each other in a circle: no order between them. */\nexport interface RecursionGroup {\n readonly size: number;\n /** `file#declaration`, sorted. */\n readonly declarations: readonly string[];\n /** The declarations among them that have findings. */\n readonly tasks: readonly string[];\n /** The files they are declared in, sorted. */\n readonly files: readonly string[];\n /** Calls that close the circle: without them it has an order. */\n readonly closingEdges: readonly ClosingCall[];\n /**\n * The cut to make when freezing a contract: the callee of a closing call with the fewest call sites in\n * the group's files. Writing its return type as a Result by hand stops changes from travelling through it.\n */\n readonly freeze: { readonly declaration: string; readonly callSites: number };\n}\n\n/** A circular group that is left of a too-large one once the imports that cannot carry a change are gone. */\nexport interface RemainingGroup {\n readonly size: number;\n readonly files: readonly string[];\n readonly tasks: readonly string[];\n /** Still more files than the threshold: it stays one work item and has an internal `order`. */\n readonly tooLarge: boolean;\n /** Imports that carry a change and close the group. */\n readonly closingEdges: readonly ClosingImport[];\n /**\n * Only when `tooLarge`: its declarations with findings (`file#declaration`) in waves, callees first.\n * A string is one declaration, an array is a recursion to change together.\n */\n readonly order?: WorkItem[][];\n /** Only when `tooLarge`: the recursions among its declarations, largest first. */\n readonly recursion?: readonly RecursionGroup[];\n}\n\nexport interface ReportedGroup {\n readonly size: number;\n readonly files: readonly string[];\n readonly tasks: readonly string[];\n readonly tooLarge: boolean;\n /** Imports that close the group: removing them is optional structural cleanup that ends the circle. */\n readonly closingEdges: readonly ClosingImport[];\n /** Only when `tooLarge`: what is left of the group without the imports that cannot carry a change. */\n readonly split?: {\n readonly droppedEdges: number;\n readonly keptEdges: number;\n readonly groups: readonly RemainingGroup[];\n };\n}\n\n/** What `trust refactor --json` prints. */\nexport interface RefactorReport {\n /** Waves in order; a string is one file, an array is a circular group to refactor together. */\n readonly waves: WorkItem[][];\n /** Every circular group of the import graph, largest first. */\n readonly cycles: readonly ReportedGroup[];\n readonly warnings: readonly ComputedImportWarning[];\n readonly summary: {\n /** Files in the graph. */\n readonly files: number;\n /** Import edges between them. */\n readonly edges: number;\n /** Files with findings. */\n readonly tasks: number;\n /** Work items (files and groups) over all waves. */\n readonly items: number;\n readonly ignored: number;\n /** `baseline`: tasks are the baseline's files; `check`: tasks are the files a fresh check found findings in. */\n readonly taskSource: 'baseline' | 'check';\n readonly baseline: string | null;\n readonly valueOnly: boolean;\n readonly maxGroupSize: number;\n };\n}\n\nfunction hasFindings(byRule: Record<string, Record<string, number>>): boolean {\n return Object.values(byRule).some((byOrigin) => Object.values(byOrigin).some((count) => count > 0));\n}\n\nfunction byName(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** One file of the walk, kept to read its calls when its group needs an internal order. */\ninterface Loaded {\n readonly ts: TypeScript;\n readonly program: TS.Program;\n readonly sourceFile: TS.SourceFile;\n}\n\ninterface InternalOrder {\n readonly order: WorkItem[][];\n readonly recursion: RecursionGroup[];\n}\n\n/**\n * The order inside one circular group, from the calls between its declarations. A declaration is\n * work when a fresh check has a finding in it and its file is a task; the others only carry the order.\n */\nfunction internalOrder(\n group: CircularGroup,\n loaded: ReadonlyMap<string, Loaded>,\n config: TrustConfig,\n keyOfTarget: (target: string) => string | undefined,\n maxGroupSize: number,\n): InternalOrder {\n const inGroup = new Set(group.files);\n const taskFiles = new Set(group.tasks);\n /** caller → callee → call sites, as `file#declaration`. */\n const calls = new Map<string, Map<string, number>>();\n const declarations = new Set<string>();\n const withFindings = new Set<string>();\n for (const file of group.files) {\n const entry = loaded.get(file);\n if (!entry) continue;\n const { ts, program, sourceFile } = entry;\n const checker = program.getTypeChecker();\n const policy = policyFor(ts, checker, config);\n for (const call of collectCalls(ts, policy, changeOracleFor(ts, checker, policy), sourceFile)) {\n const targetFile = keyOfTarget(policy.zones.virtualPaths.get(call.targetFile) ?? call.targetFile);\n if (targetFile === undefined || !inGroup.has(targetFile)) continue;\n const from = `${file}#${call.from}`;\n const to = `${targetFile}#${call.to}`;\n if (from === to) continue;\n declarations.add(from).add(to);\n let callees = calls.get(from);\n if (!callees) {\n callees = new Map();\n calls.set(from, callees);\n }\n callees.set(to, (callees.get(to) ?? 0) + 1);\n }\n if (!taskFiles.has(file)) continue;\n for (const finding of checkSourceFile({ ts, program, config, sourceFile })) {\n const declaration = `${file}#${declarationAt(ts, sourceFile, finding.line, finding.column)}`;\n declarations.add(declaration);\n withFindings.add(declaration);\n }\n }\n\n const callSites = (from: string, to: string): number => calls.get(from)?.get(to) ?? 0;\n const incoming = new Map<string, number>();\n for (const callees of calls.values()) {\n for (const [callee, count] of callees) incoming.set(callee, (incoming.get(callee) ?? 0) + count);\n }\n const plan = planRefactor({\n files: [...declarations],\n dependencies: new Map([...calls].map(([from, callees]) => [from, [...callees.keys()]])),\n tasks: withFindings,\n maxGroupSize,\n weight: callSites,\n });\n const recursion = plan.cycles.map((cycle): RecursionGroup => {\n const cuts = [...new Set(cycle.closingEdges.map((edge) => edge.to))]\n .map((declaration) => ({ declaration, callSites: incoming.get(declaration) ?? 0 }))\n .sort((a, b) => a.callSites - b.callSites || byName(a.declaration, b.declaration));\n return {\n size: cycle.size,\n declarations: cycle.files,\n tasks: cycle.tasks,\n files: [...new Set(cycle.files.map((declaration) => declaration.slice(0, declaration.indexOf('#'))))].sort(),\n closingEdges: cycle.closingEdges.map((edge) => ({ ...edge, callSites: callSites(edge.from, edge.to) })),\n freeze: cuts[0],\n };\n });\n return { order: plan.waves, recursion };\n}\n\nfunction formatItem(item: WorkItem, tooLarge: boolean): string[] {\n if (typeof item === 'string') return [` ${item}`];\n const how = tooLarge ? 'circular imports, too large for one unit: follow its internal order below' : 'circular imports, refactor together';\n return [` group of ${item.length} (${how}):`, ...item.map((file) => ` ${file}`)];\n}\n\nfunction formatClosingImport(edge: ClosingImport): string {\n return `closed by: ${edge.from} imports ${edge.names.join(', ')} from ${edge.to}`;\n}\n\nfunction formatDeclarations(item: WorkItem): string {\n return typeof item === 'string' ? item : `(${item.join(' + ')})`;\n}\n\nfunction formatRecursion(group: RecursionGroup, indent: string): string[] {\n return [\n `${indent}${group.declarations.join(', ')}`,\n ...group.closingEdges.map((edge) => `${indent} closed by: ${edge.from} calls ${edge.to} (${edge.callSites} call site(s))`),\n `${indent} freeze a contract: write the return type of ${group.freeze.declaration} as a Result by hand (${group.freeze.callSites} call site(s) in the group); changes stop there`,\n `${indent} or iterate to a fixed point: refactor these declarations in passes until their inferred failure types stop growing (they only grow, so it ends)`,\n ];\n}\n\nfunction formatRemaining(group: RemainingGroup, maxGroupSize: number, indent: string): string[] {\n const tooLarge = group.tooLarge ? ` — still too large for one unit (more than ${maxGroupSize} files)` : '';\n const lines = [`${indent}${group.size} file(s), ${group.tasks.length} with findings${tooLarge}: ${group.files.join(', ')}`];\n for (const edge of group.closingEdges) lines.push(`${indent} ${formatClosingImport(edge)}`);\n const { order, recursion } = group;\n if (order) {\n const count = order.reduce((sum, wave) => sum + wave.reduce((inWave, item) => inWave + (typeof item === 'string' ? 1 : item.length), 0), 0);\n lines.push(count === 0 ? `${indent} internal order: no declaration with findings` : `${indent} internal order of the ${count} declaration(s) with findings, callees first:`);\n order.forEach((wave, index) => lines.push(`${indent} ${index + 1}. ${wave.map(formatDeclarations).join(', ')}`));\n }\n if (recursion && recursion.length > 0) {\n lines.push(`${indent} mutual recursion (${recursion.length}): declarations that call each other in a circle, with two ways out`);\n for (const circle of recursion) lines.push(...formatRecursion(circle, `${indent} `));\n }\n return lines;\n}\n\nfunction formatCycle(cycle: ReportedGroup, maxGroupSize: number): string[] {\n const tooLarge = cycle.tooLarge ? ` — too large for one unit (more than ${maxGroupSize} files)` : '';\n const lines = [` ${cycle.size} file(s), ${cycle.tasks.length} with findings${tooLarge}: ${cycle.files.join(', ')}`];\n for (const edge of cycle.closingEdges) lines.push(` ${formatClosingImport(edge)}`);\n const split = cycle.split;\n if (!split) return lines;\n const left = split.groups.length === 0 ? 'no circular group left' : `${split.groups.length} circular group(s) left`;\n lines.push(` without the ${split.droppedEdges} import(s) that cannot carry a change (${split.keptEdges} kept): ${left}`);\n for (const group of split.groups) lines.push(...formatRemaining(group, maxGroupSize, ' '));\n return lines;\n}\n\nfunction formatReport(report: RefactorReport): string[] {\n const { waves, cycles, warnings, summary } = report;\n // The groups of the plan that are still above the threshold, by their first task (the first file of their work item).\n const tooLarge = new Set<string>();\n for (const cycle of cycles) {\n for (const group of cycle.split ? cycle.split.groups : [cycle]) {\n if (group.tooLarge && group.tasks.length > 1) tooLarge.add(group.tasks[0]);\n }\n }\n const lines: string[] = [];\n waves.forEach((wave, index) => {\n lines.push(`Wave ${index + 1} of ${waves.length} (${wave.length} item(s)):`);\n for (const item of wave) lines.push(...formatItem(item, typeof item !== 'string' && tooLarge.has(item[0])));\n });\n if (waves.length === 0) lines.push('No file with findings: nothing to refactor.');\n if (cycles.length > 0) {\n lines.push(`Circular import groups (${cycles.length}):`);\n for (const cycle of cycles) lines.push(...formatCycle(cycle, summary.maxGroupSize));\n }\n if (warnings.length > 0) {\n lines.push(`Computed import() the graph cannot follow (${warnings.length}):`);\n for (const warning of warnings) lines.push(` ${warning.file}:${warning.line}:${warning.column} import(${warning.specifier})`);\n }\n const source = summary.taskSource === 'baseline' ? `the baseline ${summary.baseline}` : 'a fresh check (no baseline file)';\n const imports = summary.valueOnly ? 'value import(s)' : 'import(s)';\n lines.push(\n `${summary.tasks} file(s) with findings in ${summary.items} work item(s) over ${waves.length} wave(s); ` +\n `${summary.files} file(s) and ${summary.edges} ${imports} in the graph, ${summary.ignored} ignored file(s) skipped; findings from ${source}.`,\n );\n return lines;\n}\n\n/** Returns the process exit code: 0 plan printed, 2 could not run (TypeScript, an unloadable file, an unreadable or missing baseline). */\nexport async function runRefactorCommand(options: RefactorCommandOptions): Promise<number> {\n const maxGroupSize = options.maxGroupSize ?? DEFAULT_MAX_GROUP_SIZE;\n if (!Number.isInteger(maxGroupSize) || maxGroupSize < 1) {\n options.log('trust refactor: --max-group needs a whole number of files, 1 or more');\n return 2;\n }\n const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ['.']);\n if ('missing' in resolved) {\n options.log(`trust refactor: no such file or directory: ${resolved.missing}`);\n return 2;\n }\n const configPath = resolve(options.cwd, options.configFile);\n const rootDir = options.root === undefined ? undefined : resolve(options.cwd, options.root);\n const config = existsSync(configPath)\n ? loadTrustConfig(configPath, { rootDir })\n : emptyTrustConfig(rootDir ?? options.cwd);\n logUnmatchedGlobs(options.log, 'refactor', config);\n const zones = new Zones(config.rootDir, config.passthrough, config.ignore);\n const files = resolved.files.filter((file) => zones.zoneOf(file) !== 'ignore');\n\n // The baseline names the tasks when there is one. A baseline named on the command line must exist.\n const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, 'trust-baseline.json'));\n const fromBaseline = existsSync(baselineFile);\n if (!fromBaseline && options.baselineFile !== undefined) {\n options.log(`trust refactor: no such baseline: ${options.baselineFile}`);\n return 2;\n }\n const baseline = readBaseline(baselineFile);\n if ('error' in baseline) {\n options.log(`trust refactor: could not read the baseline: ${baseline.error}`);\n return 2;\n }\n\n // Graph nodes are baseline keys. Programs name files their own way, so targets are matched by path, then by realpath.\n const keyByPath = new Map<string, string>();\n for (const file of files) {\n const key = relativeTo(config.rootDir, file);\n keyByPath.set(file, key);\n keyByPath.set(realpathOrSelf(file), key);\n }\n const keyOfTarget = (target: string): string | undefined => {\n if (!keyByPath.has(target)) {\n const key = keyByPath.get(realpathOrSelf(target));\n if (key === undefined) return undefined;\n keyByPath.set(target, key);\n }\n return keyByPath.get(target);\n };\n const outside = new Set<string>();\n\n const dependencies = new Map<string, Set<string>>();\n /** importer → imported file → the names imported, and those among them that can carry a change. */\n const imported = new Map<string, Map<string, { readonly all: Set<string>; readonly changing: Set<string> }>>();\n const loaded = new Map<string, Loaded>();\n const warnings: ComputedImportWarning[] = [];\n const checked = new Set<string>();\n const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };\n const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile, file }) => {\n const from = relativeTo(config.rootDir, file);\n const checker = program.getTypeChecker();\n const imports = collectImports(ts, program, sourceFile, changeOracleFor(ts, checker, policyFor(ts, checker, config)));\n const targets = new Map<string, { readonly all: Set<string>; readonly changing: Set<string> }>();\n for (const edge of imports.edges) {\n if ((options.valueOnly && edge.typeOnly) || outside.has(edge.target)) continue;\n const to = keyOfTarget(policyFor(ts, checker, config).zones.virtualPaths.get(edge.target) ?? edge.target);\n if (to === undefined) outside.add(edge.target);\n if (to === undefined || to === from) continue;\n let names = targets.get(to);\n if (!names) {\n names = { all: new Set(), changing: new Set() };\n targets.set(to, names);\n }\n names.all.add(edge.name);\n if (edge.carriesChange) names.changing.add(edge.name);\n }\n dependencies.set(from, new Set(targets.keys()));\n imported.set(from, targets);\n loaded.set(from, { ts, program, sourceFile });\n for (const computed of imports.computed) {\n const position = svelteFor(checker)?.position(sourceFile.fileName, computed);\n if (position !== null) warnings.push({ kind: 'computed-import', file: from, ...computed, ...position });\n }\n if (!fromBaseline && checkSourceFile({ ts, program, config, sourceFile }).length > 0) checked.add(from);\n });\n if (walk.status !== 'ok') {\n logWalkFailure(options.log, 'refactor', walk);\n return 2;\n }\n\n const nodes = [...dependencies.keys()];\n const tasks = fromBaseline ? new Set(nodes.filter((file) => Object.hasOwn(baseline.counts, file) && hasFindings(baseline.counts[file]))) : checked;\n warnings.sort((a, b) => (a.file !== b.file ? (a.file < b.file ? -1 : 1) : a.line - b.line || a.column - b.column));\n // What cutting an import costs: a name that cannot change (an interface, a constant) is cheap to move\n // to a file of its own, so the imports named as closing a group are the ones made of such names.\n const cutCost = (from: string, to: string): number => {\n const names = imported.get(from)?.get(to);\n return names ? names.changing.size * CHANGING_NAME_COST + (names.all.size - names.changing.size) : 1;\n };\n const plan = planRefactor({\n files: nodes,\n dependencies,\n tasks,\n maxGroupSize,\n weight: cutCost,\n carriesChange: (from, to) => (imported.get(from)?.get(to)?.changing.size ?? 1) > 0,\n });\n const closing = (edges: readonly PlanEdge[], which: 'all' | 'changing'): ClosingImport[] => {\n return edges.map(({ from, to }) => ({ from, to, names: [...(imported.get(from)?.get(to)?.[which] ?? [])].sort() }));\n };\n const remaining = (group: CircularGroup): RemainingGroup => ({\n size: group.size,\n files: group.files,\n tasks: group.tasks,\n tooLarge: group.tooLarge,\n closingEdges: closing(group.closingEdges, 'changing'),\n ...(group.tooLarge ? internalOrder(group, loaded, config, keyOfTarget, maxGroupSize) : {}),\n });\n const cycles = plan.cycles.map((cycle): ReportedGroup => {\n const split = cycle.split;\n return {\n size: cycle.size,\n files: cycle.files,\n tasks: cycle.tasks,\n tooLarge: cycle.tooLarge,\n closingEdges: closing(cycle.closingEdges, 'all'),\n ...(split ? { split: { droppedEdges: split.droppedEdges, keptEdges: split.keptEdges, groups: split.groups.map(remaining) } } : {}),\n };\n });\n const report: RefactorReport = {\n waves: plan.waves,\n cycles,\n warnings,\n summary: {\n files: nodes.length,\n edges: [...dependencies.values()].reduce((sum, targets) => sum + targets.size, 0),\n tasks: tasks.size,\n items: plan.waves.reduce((sum, wave) => sum + wave.length, 0),\n ignored: resolved.files.length - files.length,\n taskSource: fromBaseline ? 'baseline' : 'check',\n baseline: fromBaseline ? baselineFile : null,\n valueOnly: options.valueOnly,\n maxGroupSize,\n },\n };\n if (options.json) options.log(JSON.stringify(report, null, 2));\n else for (const line of formatReport(report)) options.log(line);\n return 0;\n}\n","// The calls of one source file, between declarations (no ESLint). Files that import each other in a\n// circle usually do not call each other in a circle, so inside a circular-import group the order is\n// taken from the declarations: `c.ts#load` before `d.ts#save` when `save` calls `load`.\n//\n// A declaration is named by where it sits at the top of its file: `load`, `Store.load` (a class\n// member), `Config.read` (inside a namespace), `default` (an unnamed default export), and\n// TOP_LEVEL for statements that belong to no declaration. Code nested inside a declaration (a\n// callback, an inner function) belongs to it. The callee of a call is what TrustPolicy.calleeDeclaration\n// resolves it to; a call counts only when the callee can change (change.ts): a call through an\n// interface member, to a `.d.ts` declaration or to a function with a frozen Result contract does not.\nimport { svelteForSource } from './svelte.js';\nimport type * as TS from 'typescript';\nimport type { TrustPolicy } from '../eslint/policy.js';\nimport type { TypeScript } from '../eslint/typescript.js';\nimport type { ChangeOracle } from './change.js';\n\n/** The name of the statements of a file that belong to no declaration. */\nexport const TOP_LEVEL = '(top level)';\n\n/** One call site. */\nexport interface CallEdge {\n /** The declaration the call is written in. */\n readonly from: string;\n /** File name, as the program names it, of the file that declares the callee. */\n readonly targetFile: string;\n /** The declaration called, named within `targetFile`. */\n readonly to: string;\n}\n\nfunction memberName(ts: TypeScript, member: TS.ClassElement): string | undefined {\n if (ts.isConstructorDeclaration(member)) return 'constructor';\n const name = member.name;\n if (!name) return undefined;\n return ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : undefined;\n}\n\n/** `chain[index]` is a statement of the file or of a namespace body; the nodes after it lead down to the node being named. */\nfunction nameIn(ts: TypeScript, chain: readonly TS.Node[], index: number, prefix: string): string | null {\n const statement = chain[index];\n if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) return null;\n if (ts.isFunctionDeclaration(statement)) return prefix + (statement.name?.text ?? 'default');\n if (ts.isClassDeclaration(statement)) {\n const owner = prefix + (statement.name?.text ?? 'default');\n const member = chain.at(index + 1);\n const name = member && ts.isClassElement(member) ? memberName(ts, member) : undefined;\n return name === undefined ? owner : `${owner}.${name}`;\n }\n if (ts.isVariableStatement(statement)) {\n const declaration = chain.at(index + 2);\n return prefix + (declaration && ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) ? declaration.name.text : TOP_LEVEL);\n }\n if (ts.isModuleDeclaration(statement)) {\n const inner = `${prefix}${statement.name.text}.`;\n const body = chain.at(index + 1);\n // `namespace A.B {}` nests a ModuleDeclaration directly; `namespace A {}` has a block of statements.\n if (body && ts.isModuleDeclaration(body)) return nameIn(ts, chain, index + 1, inner);\n if (body && ts.isModuleBlock(body) && chain.length > index + 2) return nameIn(ts, chain, index + 2, inner);\n return prefix + statement.name.text;\n }\n if (ts.isExportAssignment(statement)) return `${prefix}default`;\n return prefix + TOP_LEVEL;\n}\n\n/** The declaration a node belongs to; null for the file itself and for a node inside a type or an enum. */\nexport function declarationOf(ts: TypeScript, node: TS.Node): string | null {\n const chain: TS.Node[] = [];\n for (let current = node; !ts.isSourceFile(current); current = current.parent) chain.push(current);\n if (chain.length === 0) return null;\n chain.reverse();\n // The converter's render function is a scope, not a user declaration.\n const virtual = svelteForSource(node.getSourceFile());\n const render = virtual && chain.findIndex(part => ts.isFunctionDeclaration(part) && part.name?.text === '$$render');\n const index = typeof render === 'number' && render >= 0 ? render + 2 : 0;\n return index < chain.length ? nameIn(ts, chain, index, '') : TOP_LEVEL;\n}\n\n/** The declaration at a 1-based line and column, as findings report them; TOP_LEVEL when there is none. */\nexport function declarationAt(ts: TypeScript, sourceFile: TS.SourceFile, line: number, column: number): string {\n const generated = svelteForSource(sourceFile)?.generatedPositions(sourceFile.fileName, { line, column })[0];\n const position = ts.getPositionOfLineAndCharacter(sourceFile, (generated?.line ?? line) - 1, (generated?.column ?? column) - 1);\n let node: TS.Node = sourceFile;\n for (;;) {\n const child: TS.Node | undefined = ts.forEachChild(node, (candidate) => (candidate.getStart(sourceFile) <= position && position < candidate.end ? candidate : undefined));\n if (!child) break;\n node = child;\n }\n return declarationOf(ts, node) ?? TOP_LEVEL;\n}\n\n/** Every call and `new` of the file whose callee is a declaration that can change, one edge per call site. */\nexport function collectCalls(ts: TypeScript, policy: TrustPolicy, change: ChangeOracle, sourceFile: TS.SourceFile): CallEdge[] {\n const calls: CallEdge[] = [];\n const visit = (node: TS.Node): void => {\n if ((ts.isCallExpression(node) && node.expression.kind !== ts.SyntaxKind.ImportKeyword) || ts.isNewExpression(node)) {\n const from = declarationOf(ts, node);\n const callee = from === null ? null : policy.calleeDeclaration(node);\n if (from !== null && callee && change.declarationCanChange(callee.declaration)) {\n const to = declarationOf(ts, callee.declaration);\n if (to !== null) calls.push({ from, targetFile: callee.declaration.getSourceFile().fileName, to });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return calls;\n}\n","// What the refactor can change, as the importers and callers of a declaration see it. An import or a\n// call orders two files only when a change can travel through it:\n// - a function, method, accessor or constructor with a body can change: its inferred types follow\n// what it calls, and the refactor moves its failures into its return type. A written return type\n// that is a Result from @noego/trust is a frozen contract: that function cannot change;\n// - an interface, a type alias, an annotated variable or property, and a signature without a body\n// are declared types: they change only through what they mention (`typeof load`, a class);\n// - an enum, a literal constant and anything declared in a `.d.ts` file cannot change;\n// - a class can change when a member or its base class can, a module when one of its exports can;\n// - whatever these rules do not cover can change. That is the safe answer: the edge is kept.\n// Runs on TypeScript alone (no ESLint).\nimport type * as TS from 'typescript';\nimport type { TrustPolicy } from '../eslint/policy.js';\nimport type { TypeScript } from '../eslint/typescript.js';\n\nexport class ChangeOracle {\n private readonly known = new Map<TS.Node, boolean>();\n /** Declarations being judged right now: meeting one again (a type that mentions itself) assumes \"cannot change\". */\n private readonly open = new Set<TS.Node>();\n private assumptions = 0;\n\n constructor(\n private readonly ts: TypeScript,\n private readonly checker: TS.TypeChecker,\n private readonly policy: TrustPolicy,\n ) {}\n\n /** Can what the symbol names change? Follows an import to what it imports; a symbol nothing declares can. */\n symbolCanChange(symbol: TS.Symbol | undefined): boolean {\n if (!symbol) return true;\n const target = symbol.flags & this.ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;\n const declarations = target.declarations ?? [];\n return declarations.length === 0 || declarations.some((declaration) => this.declarationCanChange(declaration));\n }\n\n declarationCanChange(declaration: TS.Node): boolean {\n const known = this.known.get(declaration);\n if (known !== undefined) return known;\n if (this.open.has(declaration)) {\n this.assumptions += 1;\n return false;\n }\n this.open.add(declaration);\n const before = this.assumptions;\n const result = this.judge(declaration);\n this.open.delete(declaration);\n // \"Cannot change\" that leaned on an assumption is final only once nothing is being judged anymore.\n if (result || this.assumptions === before || this.open.size === 0) this.known.set(declaration, result);\n return result;\n }\n\n private judge(node: TS.Node): boolean {\n const ts = this.ts;\n // A `.d.ts` file is not what is being refactored.\n if (node.getSourceFile().isDeclarationFile) return false;\n if (ts.isSourceFile(node)) return this.exportsCanChange(node);\n if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return this.mentionsChange(node);\n if (ts.isEnumDeclaration(node) || ts.isEnumMember(node) || ts.isTypeParameterDeclaration(node)) return false;\n if (ts.isFunctionLike(node)) {\n const body = (node as { readonly body?: TS.Node }).body;\n return body ? !this.frozen(node) : this.mentionsChange(node);\n }\n if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isParameter(node)) {\n if (node.type) return this.mentionsChange(node.type);\n if (ts.isPropertySignature(node)) return false;\n return node.initializer ? this.expressionCanChange(node.initializer) : true;\n }\n if (ts.isPropertyAssignment(node)) return this.expressionCanChange(node.initializer);\n if (ts.isExportAssignment(node)) return this.expressionCanChange(node.expression);\n if (ts.isClassLike(node)) {\n const base = (node.heritageClauses ?? []).filter((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);\n return base.some((clause) => this.mentionsChange(clause)) || node.members.some((member) => this.memberCanChange(member));\n }\n return true;\n }\n\n private memberCanChange(member: TS.ClassElement): boolean {\n const ts = this.ts;\n if (ts.isClassStaticBlockDeclaration(member) || ts.isSemicolonClassElement(member)) return false;\n return this.declarationCanChange(member);\n }\n\n private exportsCanChange(sourceFile: TS.SourceFile): boolean {\n const module = this.checker.getSymbolAtLocation(sourceFile);\n // Not a module (no import or export): nothing to import from it.\n if (!module) return false;\n return this.checker.getExportsOfModule(module).some((exported) => this.symbolCanChange(exported));\n }\n\n /** A written return type that is a Result (or a promise of one) and mentions nothing that can change. */\n private frozen(node: TS.SignatureDeclaration): boolean {\n if (!node.type) return false;\n const written = this.checker.getTypeFromTypeNode(node.type);\n const awaited = this.checker.getAwaitedType(written) ?? written;\n return this.policy.isResultType(awaited) && !this.mentionsChange(node.type);\n }\n\n /** The type of a value without a written type: fixed for a literal, open for a call, a name or anything computed. */\n private expressionCanChange(expression: TS.Expression): boolean {\n const ts = this.ts;\n if (ts.isParenthesizedExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) {\n return this.expressionCanChange(expression.expression);\n }\n if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) {\n return ts.isConstTypeReference(expression.type) ? this.expressionCanChange(expression.expression) : this.mentionsChange(expression.type);\n }\n if (ts.isLiteralExpression(expression) || ts.isTemplateExpression(expression)) return false;\n const kind = expression.kind;\n if (kind === ts.SyntaxKind.TrueKeyword || kind === ts.SyntaxKind.FalseKeyword || kind === ts.SyntaxKind.NullKeyword) return false;\n if (ts.isPrefixUnaryExpression(expression)) return this.expressionCanChange(expression.operand);\n if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression) || ts.isClassExpression(expression)) return this.declarationCanChange(expression);\n if (ts.isArrayLiteralExpression(expression)) {\n return expression.elements.some((element) => ts.isSpreadElement(element) || this.expressionCanChange(element));\n }\n if (ts.isObjectLiteralExpression(expression)) return expression.properties.some((property) => this.declarationCanChange(property));\n return true;\n }\n\n /** Does a written type (or a declaration made of written types) name something that can change? */\n private mentionsChange(node: TS.Node): boolean {\n const ts = this.ts;\n const visit = (child: TS.Node): boolean => {\n if (ts.isTypeReferenceNode(child) && this.symbolCanChange(this.named(child.typeName))) return true;\n if (ts.isTypeQueryNode(child) && this.symbolCanChange(this.named(child.exprName))) return true;\n if (ts.isExpressionWithTypeArguments(child)) {\n const expression = child.expression;\n if (this.symbolCanChange(this.checker.getSymbolAtLocation(ts.isPropertyAccessExpression(expression) ? expression.name : expression))) return true;\n }\n if (ts.isImportTypeNode(child)) {\n const name = child.qualifier ?? (ts.isLiteralTypeNode(child.argument) ? child.argument.literal : undefined);\n if (!name || this.symbolCanChange(ts.isStringLiteral(name) ? this.checker.getSymbolAtLocation(name) : this.named(name as TS.EntityName))) return true;\n }\n return ts.forEachChild(child, visit) ?? false;\n };\n return visit(node);\n }\n\n private named(name: TS.EntityName): TS.Symbol | undefined {\n return this.checker.getSymbolAtLocation(this.ts.isQualifiedName(name) ? name.right : name);\n }\n}\n\nconst oracles = new WeakMap<TrustPolicy, ChangeOracle>();\n\n/** One oracle per policy (so per checker and config): its verdicts are cached across files. */\nexport function changeOracleFor(ts: TypeScript, checker: TS.TypeChecker, policy: TrustPolicy): ChangeOracle {\n let oracle = oracles.get(policy);\n if (!oracle) {\n oracle = new ChangeOracle(ts, checker, policy);\n oracles.set(policy, oracle);\n }\n return oracle;\n}\n","// The static imports of one source file, resolved with its program's checker (no ESLint):\n// - a named or default import, and a named re-export, points at the file that declares the name,\n// so a barrel (`export { a } from './a'`) is looked through instead of becoming an edge itself;\n// - `import * as`, `export *`, `import x = require()`, a bare `import './x'` and `import('./x')`\n// point at the module file;\n// - `import('./x').T` in a type position counts as a type-only import;\n// - `import(expression)` with a computed specifier cannot be followed and is returned separately.\n// Targets are the program's file names; the caller keeps the ones that belong to its graph.\n// With a ChangeOracle every edge also says whether a change can travel through it (change.ts).\nimport type * as TS from 'typescript';\nimport type { TypeScript } from '../eslint/typescript.js';\nimport type { ChangeOracle } from './change.js';\nimport { startOf } from './check-file.js';\n\n/** The `name` of an edge to a module as a whole (`import * as`, `export *`, `import './x'`, `import('./x')`). */\nexport const WHOLE_MODULE = '*';\n\nexport interface ImportEdge {\n /** File name, as the program names it, of the file depended on. */\n readonly target: string;\n /** Written as type-only (`import type`, `export type`, `{ type X }`, or an `import()` type). */\n readonly typeOnly: boolean;\n /** The imported name as its module exports it (`default` for a default import), or WHOLE_MODULE. */\n readonly name: string;\n /**\n * Can a change of what is imported reach this file? False for an interface, a constant, a function\n * with a frozen Result contract, an import that binds nothing… Always true without a ChangeOracle.\n */\n readonly carriesChange: boolean;\n}\n\n/** An `import(...)` whose specifier is not a string literal. `line`/`column` are 1-based. */\nexport interface ComputedImport {\n readonly line: number;\n readonly column: number;\n /** Source text of the specifier expression. */\n readonly specifier: string;\n}\n\nexport interface FileImports {\n readonly edges: readonly ImportEdge[];\n readonly computed: readonly ComputedImport[];\n}\n\nconst resolutionCaches = new WeakMap<TS.Program, TS.ModuleResolutionCache>();\n\nfunction resolutionCache(ts: TypeScript, program: TS.Program): TS.ModuleResolutionCache {\n let cache = resolutionCaches.get(program);\n if (!cache) {\n cache = ts.createModuleResolutionCache(program.getCurrentDirectory(), (name) => name, program.getCompilerOptions());\n resolutionCaches.set(program, cache);\n }\n return cache;\n}\n\nfunction declarationFiles(symbol: TS.Symbol | undefined): string[] {\n return [...new Set((symbol?.declarations ?? []).map((declaration) => declaration.getSourceFile().fileName))];\n}\n\n/** What one import resolves to: the file(s) depended on, and whether a change can come through. */\ninterface Imported {\n readonly files: readonly string[];\n readonly carriesChange: boolean;\n}\n\nexport function collectImports(ts: TypeScript, program: TS.Program, sourceFile: TS.SourceFile, change?: ChangeOracle): FileImports {\n const checker = program.getTypeChecker();\n const edges: ImportEdge[] = [];\n const computed: ComputedImport[] = [];\n\n const add = (imported: Imported, name: string, typeOnly: boolean): void => {\n for (const target of imported.files) edges.push({ target, typeOnly, name, carriesChange: imported.carriesChange });\n };\n\n /** The file(s) of the module a specifier names; none for a package without sources or an unresolved import. */\n const moduleFiles = (specifier: TS.Expression): string[] => {\n const declared = declarationFiles(checker.getSymbolAtLocation(specifier));\n if (declared.length > 0 || !ts.isStringLiteralLike(specifier)) return declared;\n // A file with no import/export is not a module to the checker (`import './polyfill'`): resolve it by name.\n const resolved = ts.resolveModuleName(specifier.text, sourceFile.fileName, program.getCompilerOptions(), ts.sys, resolutionCache(ts, program));\n return resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : [];\n };\n\n /** The module as a whole: a change comes through when one of its exports can change. */\n const wholeModule = (specifier: TS.Expression): Imported => {\n return { files: moduleFiles(specifier), carriesChange: change ? change.symbolCanChange(checker.getSymbolAtLocation(specifier)) : true };\n };\n\n /** An import that binds no name (`import './x'`, `import {} from './x'`): the module is loaded, nothing of it is used. */\n const loadedOnly = (specifier: TS.Expression): Imported => {\n return { files: moduleFiles(specifier), carriesChange: change === undefined };\n };\n\n /** The file(s) declaring an imported name, looking through re-exports; the module file when the name does not resolve. */\n const declaring = (name: TS.Node, specifier: TS.Expression): Imported => {\n const symbol = checker.getSymbolAtLocation(name);\n const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;\n const declared = declarationFiles(target);\n if (declared.length === 0) return { files: moduleFiles(specifier), carriesChange: true };\n return { files: declared, carriesChange: change ? change.symbolCanChange(target) : true };\n };\n\n const visitImport = (node: TS.ImportDeclaration): void => {\n const clause = node.importClause;\n if (!clause) {\n add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, false);\n return;\n }\n if (clause.name) add(declaring(clause.name, node.moduleSpecifier), 'default', clause.isTypeOnly);\n const bindings = clause.namedBindings;\n if (!bindings) return;\n if (ts.isNamespaceImport(bindings)) {\n add(wholeModule(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);\n return;\n }\n // `import {} from './x'` still loads the module.\n if (bindings.elements.length === 0) add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);\n for (const element of bindings.elements) {\n add(declaring(element.name, node.moduleSpecifier), (element.propertyName ?? element.name).text, clause.isTypeOnly || element.isTypeOnly);\n }\n };\n\n const visitExport = (node: TS.ExportDeclaration, specifier: TS.Expression): void => {\n const clause = node.exportClause;\n if (!clause || !ts.isNamedExports(clause)) {\n add(wholeModule(specifier), WHOLE_MODULE, node.isTypeOnly);\n return;\n }\n if (clause.elements.length === 0) add(loadedOnly(specifier), WHOLE_MODULE, node.isTypeOnly);\n for (const element of clause.elements) {\n add(declaring(element.name, specifier), (element.propertyName ?? element.name).text, node.isTypeOnly || element.isTypeOnly);\n }\n };\n\n const visitImportType = (node: TS.ImportTypeNode): void => {\n if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal)) return;\n const specifier = node.argument.literal;\n let name = node.qualifier;\n while (name && ts.isQualifiedName(name)) name = name.left;\n if (name) add(declaring(name, specifier), name.text, true);\n else add(wholeModule(specifier), WHOLE_MODULE, true);\n };\n\n const visitDynamicImport = (node: TS.CallExpression): void => {\n const specifier = node.arguments.at(0);\n if (!specifier) return;\n if (ts.isStringLiteralLike(specifier)) add(wholeModule(specifier), WHOLE_MODULE, false);\n else computed.push({ ...startOf(ts, sourceFile, specifier), specifier: specifier.getText(sourceFile) });\n };\n\n const visit = (node: TS.Node): void => {\n if (ts.isImportDeclaration(node)) visitImport(node);\n else if (ts.isExportDeclaration(node) && node.moduleSpecifier) visitExport(node, node.moduleSpecifier);\n else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {\n add(wholeModule(node.moduleReference.expression), WHOLE_MODULE, node.isTypeOnly);\n } else if (ts.isImportTypeNode(node)) visitImportType(node);\n else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) visitDynamicImport(node);\n ts.forEachChild(node, visit);\n };\n visit(sourceFile);\n return { edges, computed };\n}\n","// Dependency-ordered refactor plan over a file import graph (no TypeScript, no ESLint):\n// 1. strongly connected components (Tarjan) become units: a circular-import group changes together;\n// 2. the condensed graph is layered into waves: a unit's wave comes after the waves of everything\n// it imports, so the leaves are wave one and units of one wave can be refactored in parallel;\n// 3. only files with findings (\"tasks\") are work; a finding-free file is not in the plan, but the\n// order it imposes is kept: its importers still come after its imports;\n// 4. every circular group names a small set of edges that close its cycles, and a group above the\n// size threshold is planned again without the edges that cannot carry a change.\n// File names are opaque keys here (the command uses baseline keys, and `file#declaration` keys for\n// the call graph inside a group).\n\n/** One agent's work: a file, or the files of one circular-import group that must change together. */\nexport type WorkItem = string | string[];\n\n/** `from` depends on `to`: a file imports a file, or a declaration calls a declaration. */\nexport interface PlanEdge {\n readonly from: string;\n readonly to: string;\n}\n\nexport interface CircularGroup {\n readonly size: number;\n /** Every file of the cycle, sorted. */\n readonly files: readonly string[];\n /** The files of the cycle that have findings (the group's work item), sorted. */\n readonly tasks: readonly string[];\n /** More files than `maxGroupSize`: too large for one unit of work. */\n readonly tooLarge: boolean;\n /** Edges inside the group that close its cycles: without them the group has no cycle. A small set, not always the smallest. */\n readonly closingEdges: readonly PlanEdge[];\n /** Only on a too-large group planned with `carriesChange`: what is left of it. */\n readonly split?: GroupSplit;\n}\n\n/** What is left of a too-large group without the edges that cannot carry a change. */\nexport interface GroupSplit {\n /** Edges inside the group that cannot carry a change: left out of the plan. */\n readonly droppedEdges: number;\n /** Edges inside the group that can carry a change. */\n readonly keptEdges: number;\n /** The circular groups still inside it (none when it fell apart), largest first; `closingEdges` are edges that carry a change. */\n readonly groups: readonly CircularGroup[];\n}\n\nexport interface RefactorPlan {\n /** `waves[n]` can start when `waves[n - 1]` is done; the items of one wave are independent. */\n readonly waves: WorkItem[][];\n /** Every circular-import group (two files or more), largest first. */\n readonly cycles: CircularGroup[];\n}\n\nexport interface RefactorPlanInput {\n /** Every file of the graph. */\n readonly files: readonly string[];\n /** file → the files it imports. Files not in `files` and self-imports are ignored. */\n readonly dependencies: ReadonlyMap<string, Iterable<string>>;\n /** The files that have findings. */\n readonly tasks: ReadonlySet<string>;\n /** A circular group with more files than this is flagged `tooLarge`. */\n readonly maxGroupSize: number;\n /** What cutting the edge `from` → `to` costs (1 when omitted). Closing edges are chosen among the cheap ones. */\n readonly weight?: (from: string, to: string) => number;\n /**\n * Can a change of `to` change `from` through this edge? When given, a too-large group is planned\n * again without the edges inside it that answer no.\n */\n readonly carriesChange?: (from: string, to: string) => boolean;\n}\n\ninterface Graph {\n readonly files: readonly string[];\n /** Per file index: the indexes of the files it imports, sorted, without itself. */\n readonly imports: readonly (readonly number[])[];\n}\n\nfunction indexGraph(files: readonly string[], dependencies: ReadonlyMap<string, Iterable<string>>): Graph {\n const sorted = [...new Set(files)].sort();\n const indexOf = new Map(sorted.map((file, index) => [file, index]));\n const imports = sorted.map((file, index) => {\n const targets = new Set<number>();\n for (const dependency of dependencies.get(file) ?? []) {\n const target = indexOf.get(dependency);\n if (target !== undefined && target !== index) targets.add(target);\n }\n return [...targets].sort((a, b) => a - b);\n });\n return { files: sorted, imports };\n}\n\n/**\n * Tarjan's algorithm, iterative (import chains can be thousands of files deep). Components come out\n * dependencies first: every component a component imports from is earlier in the list.\n */\nfunction components(graph: Graph): number[][] {\n const count = graph.files.length;\n const order = new Array<number>(count).fill(-1);\n const low = new Array<number>(count).fill(0);\n const onStack = new Array<boolean>(count).fill(false);\n const stack: number[] = [];\n const found: number[][] = [];\n let next = 0;\n\n for (let root = 0; root < count; root += 1) {\n if (order[root] !== -1) continue;\n // One frame per file being visited: the file and how many of its imports were followed.\n const frames: { readonly file: number; followed: number }[] = [];\n const open = (file: number): void => {\n order[file] = next;\n low[file] = next;\n next += 1;\n stack.push(file);\n onStack[file] = true;\n frames.push({ file, followed: 0 });\n };\n open(root);\n while (frames.length > 0) {\n const frame = frames[frames.length - 1];\n const targets = graph.imports[frame.file];\n if (frame.followed < targets.length) {\n const target = targets[frame.followed];\n frame.followed += 1;\n if (order[target] === -1) open(target);\n else if (onStack[target]) low[frame.file] = Math.min(low[frame.file], order[target]);\n continue;\n }\n frames.pop();\n if (frames.length > 0) {\n const parent = frames[frames.length - 1].file;\n low[parent] = Math.min(low[parent], low[frame.file]);\n }\n if (low[frame.file] !== order[frame.file]) continue;\n const component: number[] = [];\n for (;;) {\n const member = stack.pop() as number;\n onStack[member] = false;\n component.push(member);\n if (member === frame.file) break;\n }\n found.push(component.sort((a, b) => a - b));\n }\n }\n return found;\n}\n\n/** The strongly connected components of the import graph (each sorted), dependencies first. */\nexport function stronglyConnectedComponents(files: readonly string[], dependencies: ReadonlyMap<string, Iterable<string>>): string[][] {\n const graph = indexGraph(files, dependencies);\n return components(graph).map((component) => component.map((file) => graph.files[file]));\n}\n\nfunction firstFile(item: WorkItem): string {\n return typeof item === 'string' ? item : item[0];\n}\n\nfunction byName(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Can `to` be reached from `from` along `edges` (per file index: the indexes it points at)? */\nfunction reaches(edges: ReadonlyMap<number, ReadonlySet<number>>, from: number, to: number): boolean {\n const seen = new Set<number>([from]);\n const queue = [from];\n while (queue.length > 0) {\n const file = queue.pop() as number;\n if (file === to) return true;\n for (const target of edges.get(file) ?? []) {\n if (seen.has(target)) continue;\n seen.add(target);\n queue.push(target);\n }\n }\n return false;\n}\n\n/**\n * A small set of edges inside one component that close its cycles: without them the component has no\n * cycle. The smallest (or cheapest) such set is NP-hard to find, so this is a heuristic in two passes:\n * 1. order the members greedily (Eades, Lin and Smyth, with costs): a member that imports nothing\n * left goes last, a member nothing left imports goes first, otherwise the member whose imports\n * cost the most over its importers goes first; the edges that point backwards in that order\n * are candidates;\n * 2. put back every candidate that closes no cycle on its own, costliest first, so every edge that\n * stays closes a cycle and cheap edges are the ones cut.\n */\nfunction closingEdgesOf(graph: Graph, members: readonly number[], cost: (from: number, to: number) => number): [number, number][] {\n if (members.length < 2) return [];\n const inside = new Set(members);\n const out = new Map<number, number[]>(members.map((member) => [member, []]));\n const into = new Map<number, number[]>(members.map((member) => [member, []]));\n // Per member, over the members still to place: how many it imports and is imported by, and what those edges cost.\n const degree = new Map(members.map((member) => [member, { out: 0, in: 0, outCost: 0, inCost: 0 }]));\n const degreeOf = (member: number): { out: number; in: number; outCost: number; inCost: number } => {\n return degree.get(member) as { out: number; in: number; outCost: number; inCost: number };\n };\n for (const member of members) {\n for (const target of graph.imports[member]) {\n if (!inside.has(target)) continue;\n (out.get(member) as number[]).push(target);\n (into.get(target) as number[]).push(member);\n const edgeCost = cost(member, target);\n degreeOf(member).out += 1;\n degreeOf(member).outCost += edgeCost;\n degreeOf(target).in += 1;\n degreeOf(target).inCost += edgeCost;\n }\n }\n\n const left = new Set(members);\n const first: number[] = [];\n const last: number[] = [];\n const gap = (member: number): number => degreeOf(member).outCost - degreeOf(member).inCost;\n while (left.size > 0) {\n let sink: number | undefined;\n let source: number | undefined;\n let widest: number | undefined;\n for (const member of left) {\n if (degreeOf(member).out === 0) {\n sink = member;\n break;\n }\n if (source !== undefined) continue;\n if (degreeOf(member).in === 0) source = member;\n else if (widest === undefined || gap(member) > gap(widest)) widest = member;\n }\n const picked = (sink ?? source ?? widest) as number;\n if (sink !== undefined) last.push(picked);\n else first.push(picked);\n left.delete(picked);\n for (const target of out.get(picked) as number[]) {\n degreeOf(target).in -= 1;\n degreeOf(target).inCost -= cost(picked, target);\n }\n for (const importer of into.get(picked) as number[]) {\n degreeOf(importer).out -= 1;\n degreeOf(importer).outCost -= cost(importer, picked);\n }\n }\n\n // `first` then `last` reversed: importers before what they import. An edge pointing at an earlier member is a candidate.\n const position = new Map([...first, ...last.reverse()].map((member, index) => [member, index]));\n const kept = new Map<number, Set<number>>(members.map((member) => [member, new Set<number>()]));\n const candidates: [number, number][] = [];\n for (const member of members) {\n for (const target of out.get(member) as number[]) {\n if ((position.get(member) as number) > (position.get(target) as number)) candidates.push([member, target]);\n else (kept.get(member) as Set<number>).add(target);\n }\n }\n candidates.sort((a, b) => cost(b[0], b[1]) - cost(a[0], a[1]) || a[0] - b[0] || a[1] - b[1]);\n const closing: [number, number][] = [];\n for (const [from, to] of candidates) {\n if (reaches(kept, to, from)) closing.push([from, to]);\n else (kept.get(from) as Set<number>).add(to);\n }\n return closing.sort((a, b) => a[0] - b[0] || a[1] - b[1]);\n}\n\n/** Waves and circular groups of one indexed graph. */\nfunction planGraph(graph: Graph, input: RefactorPlanInput): { waves: WorkItem[][]; cycles: CircularGroup[] } {\n const units = components(graph);\n const unitOf = new Array<number>(graph.files.length).fill(0);\n units.forEach((members, unit) => {\n for (const member of members) unitOf[member] = unit;\n });\n const weight = input.weight;\n const cost = weight ? (from: number, to: number): number => weight(graph.files[from], graph.files[to]) : (): number => 1;\n\n // depth = how many task units lie on the longest import path below a unit. Units come dependencies\n // first, so each import's depth is final when its importer is reached. A finding-free unit adds\n // nothing itself and hands the depth of its imports on to its importers.\n const depth: number[] = [];\n const waves: WorkItem[][] = [];\n const cycles: CircularGroup[] = [];\n const work = units.map((members) => members.map((member) => graph.files[member]).filter((file) => input.tasks.has(file)));\n units.forEach((members, unit) => {\n let below = 0;\n for (const member of members) {\n for (const target of graph.imports[member]) {\n const imported = unitOf[target];\n if (imported !== unit) below = Math.max(below, depth[imported] + (work[imported].length > 0 ? 1 : 0));\n }\n }\n depth[unit] = below;\n const tasks = work[unit];\n if (members.length > 1) {\n const files = members.map((member) => graph.files[member]);\n const closingEdges = closingEdgesOf(graph, members, cost).map(([from, to]) => ({ from: graph.files[from], to: graph.files[to] }));\n cycles.push({ size: files.length, files, tasks, tooLarge: files.length > input.maxGroupSize, closingEdges });\n }\n if (tasks.length === 0) return;\n while (waves.length <= below) waves.push([]);\n waves[below].push(tasks.length === 1 ? tasks[0] : tasks);\n });\n\n for (const wave of waves) wave.sort((a, b) => byName(firstFile(a), firstFile(b)));\n cycles.sort((a, b) => b.size - a.size || byName(a.files[0], b.files[0]));\n return { waves, cycles };\n}\n\n/**\n * The plan of the import graph. With `carriesChange`, a circular group above `maxGroupSize` is shrunk\n * first: the edges inside it that cannot carry a change are left out and the graph is planned again,\n * so the waves hold what is left of the group (smaller groups and single files, in their own order).\n * `cycles` still lists the groups of the full graph; a group that was shrunk says what is left of it\n * in `split`. A group at or under the threshold, and every edge outside the too-large groups, is\n * planned as it is.\n */\nexport function planRefactor(input: RefactorPlanInput): RefactorPlan {\n const graph = indexGraph(input.files, input.dependencies);\n const full = planGraph(graph, input);\n const carriesChange = input.carriesChange;\n if (!carriesChange || !full.cycles.some((cycle) => cycle.tooLarge)) return full;\n\n const groupOf = new Map<string, number>();\n full.cycles.forEach((cycle, index) => {\n if (cycle.tooLarge) for (const file of cycle.files) groupOf.set(file, index);\n });\n const dropped = new Map<number, number>();\n const kept = new Map<number, number>();\n const imports = graph.imports.map((targets, file) => {\n const group = groupOf.get(graph.files[file]);\n if (group === undefined) return targets;\n return targets.filter((target) => {\n if (groupOf.get(graph.files[target]) !== group) return true;\n const carries = carriesChange(graph.files[file], graph.files[target]);\n const counts = carries ? kept : dropped;\n counts.set(group, (counts.get(group) ?? 0) + 1);\n return carries;\n });\n });\n const pruned = planGraph({ files: graph.files, imports }, input);\n const cycles = full.cycles.map((cycle, index) => {\n if (!cycle.tooLarge) return cycle;\n const groups = pruned.cycles.filter((left) => groupOf.get(left.files[0]) === index);\n return { ...cycle, split: { droppedEdges: dropped.get(index) ?? 0, keptEdges: kept.get(index) ?? 0, groups } };\n });\n return { waves: pruned.waves, cycles };\n}\n","#!/usr/bin/env node\n// trust — CLI for @noego/trust.\n//\n// trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig tsconfig.json] [--root <dir>]\n// trust baseline [paths…] [--config trust.config.json] [--baseline trust-baseline.json] [--update] [--tsconfig tsconfig.json] [--root <dir>]\n// trust check <paths…> [--strict] [--config trust.config.json] [--tsconfig tsconfig.json] [--root <dir>]\n// trust refactor [paths…] [--json] [--value-only] [--max-group <n>] [--config trust.config.json] [--baseline trust-baseline.json] [--tsconfig tsconfig.json] [--root <dir>]\nimport { runBaselineCommand } from './baseline-command.js';\nimport { runCheckCommand } from './check-command.js';\nimport { acquireRunLock, runLockDisabled } from './run-lock.js';\nimport { explain, formatExplanation } from './explain.js';\nimport { runRefactorCommand } from './refactor-command.js';\n\n\nconst USAGE = `Usage:\n trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]\n Print the origin each call on that line resolves to, and why it is (un)trusted: for failing\n (\"trust\" / \"distrust\") and for its types (\"trust_type\" / \"distrust_type\").\n Also prints every type claim starting on that line (type-claim): its kind and why it is a claim,\n and every untrusted value starting on it (untrusted-value): how it entered, the origin that\n declared its type, and whether its use is reported.\n trust baseline [paths...] [--config trust.config.json] [--baseline trust-baseline.json] [--update] [--tsconfig <path>] [--root <dir>]\n Check the files with TypeScript alone (no ESLint) and fail on trust violations not in the baseline.\n Files are found and skipped as in trust check; --update rewrites the baseline from the current findings.\n With paths, only the checked files' entries are reported as shrunk or rewritten by --update.\n trust check <paths...> [--strict] [--perf] [--json] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]\n Check with the native Rust engine (bundled Wasm fallback); .svelte conversion uses TypeScript in Node.\n Each file uses --tsconfig if given, else the first matching \"tsconfig\" entry of the trust config,\n else the nearest tsconfig.json above it.\n Files in the config's ignore zone are skipped. --strict also fails on written return types\n in every checked file; the config's \"strict\" globs do the same for the files they match.\n --perf adds performance warnings, which never fail the check. --json emits findings with severity.\n Exit codes: 0 clean or warnings only, 1 trust errors, 2 the check could not run.\n trust refactor [paths...] [--json] [--value-only] [--max-group <n>] [--config trust.config.json] [--baseline trust-baseline.json] [--tsconfig <path>] [--root <dir>]\n Print the order to refactor the files with findings in: waves of work items, leaves of the import\n graph first. The items of a wave can be done in parallel; a circular-import group is one item.\n Findings come from the baseline, or from a fresh check when there is no baseline file.\n --json prints { \"waves\": [[\"a.ts\", [\"b.ts\", \"c.ts\"]], [\"d.ts\"]], ... }; --value-only leaves\n type-only imports out of the graph. Every circular group lists the imports that close it.\n A circular group of more than --max-group <n> files (default 8) is too large for one item: the\n imports inside it that cannot carry a change (an interface, a constant, a written Result return\n type) are dropped; what is still too large gets an internal order of its declarations, callees\n first, and declarations that call each other in a circle are reported with the calls closing it.\n --root <dir> resolves the config's globs, tsconfig paths and baseline keys against <dir> instead of\n the config file's directory (for a config kept outside the project).`;\n\ninterface ParsedArgs {\n readonly positional: string[];\n readonly flags: Map<string, string | true>;\n}\n\n/** Flags that take no value. */\nconst BOOLEAN_FLAGS = new Set(['update', 'help', 'strict', 'json', 'value-only', 'perf']);\n\nfunction parseArgs(argv: readonly string[]): ParsedArgs {\n const positional: string[] = [];\n const flags = new Map<string, string | true>();\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n if (!arg.startsWith('--')) {\n positional.push(arg);\n continue;\n }\n const [name, inline] = arg.slice(2).split('=', 2);\n if (name === 'rs' || name === 'go') throw new Error('--rs and --go were removed; trust check uses the native engine automatically');\n if (!BOOLEAN_FLAGS.has(name) && !['config', 'tsconfig', 'root', 'baseline', 'max-group'].includes(name)) throw new Error(`unknown flag --${name}`);\n if (BOOLEAN_FLAGS.has(name) && inline !== undefined) throw new Error(`--${name} does not take a value`);\n if (inline !== undefined) flags.set(name, inline);\n else if (BOOLEAN_FLAGS.has(name)) flags.set(name, true);\n else {\n const value = argv[index + 1];\n if (value === undefined) throw new Error(`--${name} needs a value`);\n flags.set(name, value);\n index += 1;\n }\n }\n return { positional, flags };\n}\n\nfunction stringFlag(flags: Map<string, string | true>, name: string): string | undefined {\n const value = flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction parseLocation(location: string): { file: string; line: number; column?: number } {\n const match = /^(.*?):(\\d+)(?::(\\d+))?$/.exec(location);\n if (!match) throw new Error(`expected <file>:<line>[:<column>], got \"${location}\"`);\n return { file: match[1], line: Number(match[2]), column: match[3] ? Number(match[3]) : undefined };\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n const [command, ...rest] = argv;\n const { positional, flags } = parseArgs(rest);\n const cwd = process.cwd();\n const configFile = stringFlag(flags, 'config') ?? 'trust.config.json';\n if (!command || command === 'help' || flags.has('help')) {\n console.log(USAGE);\n return command ? 0 : 1;\n }\n if (command === 'explain') {\n if (positional.length !== 1) throw new Error('explain takes exactly one <file>:<line>[:<column>]');\n const location = parseLocation(positional[0]);\n const explained = explain({ cwd, configFile, tsconfig: stringFlag(flags, 'tsconfig'), root: stringFlag(flags, 'root'), ...location });\n if (explained.kind !== 'explained') {\n console.error(`trust explain: ${explained.message}`);\n return 2;\n }\n console.log(formatExplanation(explained.explanation));\n return 0;\n }\n if (command === 'baseline') {\n return runBaselineCommand({\n cwd,\n paths: positional,\n configFile,\n baselineFile: stringFlag(flags, 'baseline'),\n update: flags.get('update') === true,\n tsconfig: stringFlag(flags, 'tsconfig'),\n root: stringFlag(flags, 'root'),\n log: (line) => console.log(line),\n });\n }\n if (command === 'check') {\n return runCheckCommand({\n cwd,\n paths: positional,\n configFile,\n strict: flags.get('strict') === true,\n tsconfig: stringFlag(flags, 'tsconfig'),\n root: stringFlag(flags, 'root'),\n perf: flags.get('perf') === true,\n json: flags.get('json') === true,\n log: (line) => console.log(line),\n });\n }\n if (command === 'refactor') {\n const maxGroup = stringFlag(flags, 'max-group');\n return runRefactorCommand({\n cwd,\n paths: positional,\n configFile,\n baselineFile: stringFlag(flags, 'baseline'),\n json: flags.get('json') === true,\n valueOnly: flags.get('value-only') === true,\n maxGroupSize: maxGroup === undefined ? undefined : Number(maxGroup),\n tsconfig: stringFlag(flags, 'tsconfig'),\n root: stringFlag(flags, 'root'),\n log: (line) => console.log(line),\n });\n }\n throw new Error(`unknown command \"${command}\"\\n${USAGE}`);\n}\n\nconst HEAVY_COMMANDS = new Set(['baseline', 'check', 'refactor']);\n\n/** Heavy commands queue behind any other Trust run on this machine (see run-lock.ts). */\nasync function runExclusive(argv: readonly string[]): Promise<number> {\n const [command] = argv;\n if (!command || !HEAVY_COMMANDS.has(command) || argv.includes('--help') || runLockDisabled()) return main(argv);\n const lock = await acquireRunLock({\n onWait: () => console.error('trust: another trust run is in progress on this machine; waiting for it to finish…'),\n });\n try {\n return await main(argv);\n } finally {\n await lock.release();\n }\n}\n\nrunExclusive(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (error: unknown) => {\n console.error(`trust: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 2;\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,YAAY,qBAAqB;AAC1C,SAAS,QAAAA,OAAM,WAAAC,gBAAe;;;ACC9B,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,WAAAC,gBAAe;AAKxB,SAAS,iBAAiB;AAC1B,SAAS,cAAc;;;ACdvB,SAAS,YAAY,WAAW,cAAc,gBAAgB;AAC9D,SAAS,qBAAqB;AAC9B,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,qBAAqB;AASvB,SAAS,sBAAsB,UAAkB,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Y,MAAM;AAAA,MACvC,cAAc,aAAa,SAAY,SAAY,OAAO,QAAQ;AAAA,MAClE,UAAU,WAAW,OAAO,UAAU;AAAA,MACtC,MAAM,WAAW,OAAO,MAAM;AAAA,MAC9B,KAAK,CAAC,SAAS,QAAQ,IAAI,IAAI;AAAA,IACjC,CAAC;AAAA,EACH;AACA,QAAM,IAAI,MAAM,oBAAoB,OAAO;AAAA,EAAM,KAAK,EAAE;AAC1D;AAEA,IAAM,iBAAiB,oBAAI,IAAI,CAAC,YAAY,SAAS,UAAU,CAAC;AAGhE,eAAe,aAAa,MAA0C;AACpE,QAAM,CAAC,OAAO,IAAI;AAClB,MAAI,CAAC,WAAW,CAAC,eAAe,IAAI,OAAO,KAAK,KAAK,SAAS,QAAQ,KAAK,gBAAgB,EAAG,QAAO,KAAK,IAAI;AAC9G,QAAM,OAAO,MAAM,eAAe;AAAA,IAChC,QAAQ,MAAM,QAAQ,MAAM,yFAAoF;AAAA,EAClH,CAAC;AACD,MAAI;AACF,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,UAAE;AACA,UAAM,KAAK,QAAQ;AAAA,EACrB;AACF;AAEA,aAAa,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EAClC,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAmB;AAClB,YAAQ,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChF,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["join","resolve","readFileSync","resolve","path","readFileSync","resolve","resolve","join","existsSync","resolve","resolve","existsSync","statSync","join","resolve","resolve","resolve","found","existsSync","join","resolve","byName","resolve","existsSync","join"]}