@noego/trust 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  untrustedValueContext,
25
25
  untrustedValueMessage,
26
26
  untrustedValuesIn
27
- } from "../chunk-P4VFMA2A.js";
27
+ } from "../chunk-QTS55J43.js";
28
28
  import {
29
29
  compareFindings,
30
30
  forEachSourceFile,
@@ -34,7 +34,7 @@ import {
34
34
  logWalkFailure,
35
35
  relativeTo,
36
36
  resolveFiles
37
- } from "../chunk-V4FYZG5Q.js";
37
+ } from "../chunk-6K5I3ZRI.js";
38
38
  import {
39
39
  BOUNDARY_RULE,
40
40
  DROPPED_RESULT_RULE,
@@ -62,89 +62,22 @@ import {
62
62
  svelteFor,
63
63
  svelteForSource,
64
64
  updateBaseline
65
- } from "../chunk-RVTPDLEW.js";
65
+ } from "../chunk-4XGOH7JE.js";
66
66
 
67
67
  // src/cli/baseline-command.ts
68
68
  import { existsSync, writeFileSync } from "fs";
69
- import { join, resolve } from "path";
70
- async function runBaselineCommand(options) {
71
- const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ["."]);
72
- if ("missing" in resolved) {
73
- options.log(`trust baseline: no such file or directory: ${resolved.missing}`);
74
- return 2;
75
- }
76
- const configPath = resolve(options.cwd, options.configFile);
77
- const rootDir = options.root === void 0 ? void 0 : resolve(options.cwd, options.root);
78
- const config = existsSync(configPath) ? loadTrustConfig(configPath, { rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
79
- logUnmatchedGlobs(options.log, "baseline", config);
80
- const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, "trust-baseline.json"));
81
- const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
82
- const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
83
- const scope = options.paths.length === 0 ? WHOLE_BASELINE : { kind: "files", files: new Set(files.map((file) => relativeTo(config.rootDir, file))) };
84
- const findings = [];
85
- const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };
86
- const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile }) => {
87
- findings.push(...checkSourceFile({ ts, program, config, sourceFile }));
88
- });
89
- if (walk.status !== "ok") {
90
- logWalkFailure(options.log, "baseline", walk);
91
- return 2;
92
- }
93
- const baseline = options.update && scope.kind === "all" ? { counts: {} } : readBaseline(baselineFile);
94
- if ("error" in baseline) {
95
- options.log(`trust baseline: could not read the baseline: ${baseline.error}`);
96
- return 2;
97
- }
98
- if (options.update) {
99
- const updated = updateBaseline(baseline.counts, findings, scope);
100
- writeFileSync(baselineFile, serializeBaseline(updated.counts));
101
- const kept = updated.kept > 0 ? ` Kept the entries of ${updated.kept} unchecked file(s).` : "";
102
- options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${files.length} checked file(s).${kept}`);
103
- return 0;
104
- }
105
- const { added, stale } = compareToBaseline(findings, baseline.counts, scope);
106
- if (stale.length > 0) {
107
- options.log(`${stale.length} baseline entr${stale.length === 1 ? "y has" : "ies have"} fewer findings now; run with --update to shrink the baseline.`);
108
- }
109
- if (added.length === 0) {
110
- options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${files.length} file(s)).`);
111
- return 0;
112
- }
113
- const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);
114
- options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);
115
- for (const delta of added) for (const line of describeBaselineDelta(delta)) options.log(` ${line}`);
116
- options.log("Guard each call (try/catch returning Result.err, or Trust.try), or trust its origin in trust.config.json.");
117
- const hasTypeClaims = added.some((delta) => delta.rule === TYPE_CLAIM_RULE);
118
- if (hasTypeClaims) options.log("Prove each claimed type (narrow or validate the value) instead of asserting it.");
119
- const hasUntrustedValues = added.some((delta) => delta.rule === UNTRUSTED_VALUE_RULE);
120
- if (hasUntrustedValues) {
121
- 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.');
122
- }
123
- if (added.some((delta) => delta.rule === DROPPED_RESULT_RULE)) {
124
- options.log("Return each dropped failure (`if (!r.ok) return r;`) or handle it with Trust.decide.");
125
- }
126
- if (added.some((delta) => delta.rule === BOUNDARY_RULE)) {
127
- options.log('Decide every kind at each boundary (an exhaustive `switch`) and return plain data, or exclude it under "boundaries" in trust.config.json.');
128
- }
129
- const alsoShows = `${hasTypeClaims ? ", and why a line is a type claim" : ""}${hasUntrustedValues ? ", and where an untrusted value comes from" : ""}`;
130
- options.log(`\`trust explain <file>:<line>\` shows which origin a call resolves to${alsoShows}.`);
131
- return 1;
132
- }
133
-
134
- // src/cli/check-command.ts
135
- import { existsSync as existsSync2 } from "fs";
136
- import { resolve as resolve4 } from "path";
69
+ import { join as join2, resolve as resolve3 } from "path";
137
70
 
138
71
  // src/cli/native-check.ts
139
72
  import { readFileSync as readFileSync2 } from "fs";
140
- import { resolve as resolve3 } from "path";
73
+ import { resolve as resolve2 } from "path";
141
74
  import { spawnSync } from "child_process";
142
75
  import { Worker } from "worker_threads";
143
76
 
144
77
  // src/cli/native-engine.ts
145
78
  import { accessSync, constants, readFileSync, statSync } from "fs";
146
79
  import { createRequire } from "module";
147
- import { dirname, join as join2, resolve as resolve2 } from "path";
80
+ import { dirname, join, resolve } from "path";
148
81
  import { fileURLToPath } from "url";
149
82
  function nativePlatformPackage(platform, arch, libc = null) {
150
83
  if (platform === "darwin" && arch === "arm64") return "@noego/trust-darwin-arm64";
@@ -174,7 +107,7 @@ function runtimeLinux(platform) {
174
107
  var requireFromHere = createRequire(import.meta.url);
175
108
  function packageRoots() {
176
109
  const here = dirname(fileURLToPath(import.meta.url));
177
- const roots = [resolve2(here, "..", "..")];
110
+ const roots = [resolve(here, "..", "..")];
178
111
  try {
179
112
  roots.unshift(dirname(requireFromHere.resolve("@noego/trust/package.json")));
180
113
  } catch {
@@ -193,7 +126,7 @@ function isFile(path, executable = false, platform = process.platform) {
193
126
  function packageVersion(roots, name) {
194
127
  for (const root of roots) {
195
128
  try {
196
- const manifest = JSON.parse(readFileSync(join2(root, "package.json"), "utf8"));
129
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
197
130
  const version = manifest.optionalDependencies?.[name];
198
131
  if (manifest.name === "@noego/trust" && typeof version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) return version;
199
132
  } catch {
@@ -217,20 +150,20 @@ function nativeBinary(options = {}) {
217
150
  try {
218
151
  const manifestPath = (options.resolvePackage ?? requireFromHere.resolve)(`${name}/package.json`);
219
152
  const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
220
- const candidate = join2(dirname(manifestPath), "bin", executable);
153
+ const candidate = join(dirname(manifestPath), "bin", executable);
221
154
  if (manifest.name === name && manifest.version === version && isFile(candidate, true, platform)) return candidate;
222
155
  } catch {
223
156
  }
224
157
  }
225
- return roots.map((root) => join2(root, "native", "target", "release", executable)).find((candidate) => isFile(candidate, true, platform)) ?? null;
158
+ return roots.map((root) => join(root, "native", "target", "release", executable)).find((candidate) => isFile(candidate, true, platform)) ?? null;
226
159
  }
227
160
  function nativeWasm(options = {}) {
228
161
  const env = options.env ?? process.env;
229
162
  if (env.TRUST_NATIVE_WASM) return env.TRUST_NATIVE_WASM;
230
163
  const candidates = (options.roots ?? packageRoots()).flatMap((root) => [
231
- join2(root, "dist", "native", "trust_native_wasm.wasm"),
232
- join2(root, "native", "target", "wasm32-wasip1", "wasm", "trust_native_wasm.wasm"),
233
- join2(root, "native", "target", "wasm32-wasip1", "release", "trust_native_wasm.wasm")
164
+ join(root, "dist", "native", "trust_native_wasm.wasm"),
165
+ join(root, "native", "target", "wasm32-wasip1", "wasm", "trust_native_wasm.wasm"),
166
+ join(root, "native", "target", "wasm32-wasip1", "release", "trust_native_wasm.wasm")
234
167
  ]);
235
168
  return candidates.find((candidate) => isFile(candidate)) ?? null;
236
169
  }
@@ -246,7 +179,7 @@ function nativeEngine(options = {}) {
246
179
  }
247
180
 
248
181
  // src/cli/native-check.ts
249
- var NATIVE_PROTOCOL_VERSION = 4;
182
+ var NATIVE_PROTOCOL_VERSION = 6;
250
183
  var WASM_STACK_SIZE_MB = 256;
251
184
  var OPT_IN_RULES = [];
252
185
  function runBinary(binary, request, cwd) {
@@ -281,7 +214,7 @@ function validResponse(value) {
281
214
  if (response.version !== NATIVE_PROTOCOL_VERSION || !Array.isArray(response.findings) || !Array.isArray(response.errors)) return false;
282
215
  if (response.setupError !== null && typeof response.setupError !== "string") return false;
283
216
  if (!response.errors.every((error) => typeof error === "string")) return false;
284
- if (!response.findings.every((finding) => finding && typeof finding === "object" && ["file", "rule", "message"].every((key) => typeof finding[key] === "string") && Number.isInteger(finding.line) && finding.line > 0 && Number.isInteger(finding.column) && finding.column > 0 && (finding.severity === "error" || finding.severity === "warning"))) return false;
217
+ if (!response.findings.every((finding) => finding && typeof finding === "object" && ["file", "rule", "origin", "message"].every((key) => typeof finding[key] === "string") && Number.isInteger(finding.line) && finding.line > 0 && Number.isInteger(finding.column) && finding.column > 0 && (finding.severity === "error" || finding.severity === "warning"))) return false;
285
218
  const stats = response.stats;
286
219
  return !!stats && ["loadSeconds", "checkSeconds", "checkedFiles"].every((key) => typeof stats[key] === "number" && Number.isFinite(stats[key]) && stats[key] >= 0);
287
220
  }
@@ -330,7 +263,7 @@ async function checkNative(options) {
330
263
  extraRoots,
331
264
  programs: options.programs,
332
265
  perf: options.perf ?? false,
333
- rules: { 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"] },
266
+ 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"] },
334
267
  config: {
335
268
  levels: config.levels.map((level) => ({ source: level.source, trust: level.trust, distrust: level.distrust, typeTrust: level.typeTrust, typeDistrust: level.typeDistrust })),
336
269
  passthrough: config.passthrough.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns })),
@@ -362,14 +295,78 @@ async function checkNative(options) {
362
295
  if (response.errors.length > 0) return { findings: [], walk: { status: "file-errors", errors: response.errors.map((error) => svelte.error(error)) } };
363
296
  const snippetTrusted = decide(config.levels, (level) => level, "svelte.__renderSnippet", "svelte").trusted && !("distrustedBy" in decide(config.levels, (level) => level, "svelte.Snippet", "svelte"));
364
297
  const findings = response.findings.flatMap((finding) => {
365
- const file = resolve3(config.rootDir, finding.file);
298
+ const file = resolve2(config.rootDir, finding.file);
366
299
  const mapped = svelte.finding(file, finding, snippetTrusted);
367
300
  return mapped ? [{ ...mapped, file: svelte.paths.has(file) ? relativeTo(config.rootDir, svelte.original(file)) : finding.file }] : [];
368
301
  });
369
302
  return { findings, walk: { status: "ok" } };
370
303
  }
371
304
 
305
+ // src/cli/baseline-command.ts
306
+ async function runBaselineCommand(options) {
307
+ const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ["."]);
308
+ if ("missing" in resolved) {
309
+ options.log(`trust baseline: no such file or directory: ${resolved.missing}`);
310
+ return 2;
311
+ }
312
+ const configPath = resolve3(options.cwd, options.configFile);
313
+ const rootDir = options.root === void 0 ? void 0 : resolve3(options.cwd, options.root);
314
+ const config = existsSync(configPath) ? loadTrustConfig(configPath, { rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
315
+ logUnmatchedGlobs(options.log, "baseline", config);
316
+ const baselineFile = resolve3(options.cwd, options.baselineFile ?? join2(config.rootDir, "trust-baseline.json"));
317
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
318
+ const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
319
+ const scope = options.paths.length === 0 ? WHOLE_BASELINE : { kind: "files", files: new Set(files.map((file) => relativeTo(config.rootDir, file))) };
320
+ const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };
321
+ const { findings, walk } = await checkNative({ cwd: options.cwd, files, config, programs, strictFiles: [], log: options.log });
322
+ if (walk.status !== "ok") {
323
+ logWalkFailure(options.log, "baseline", walk);
324
+ return 2;
325
+ }
326
+ const baseline = options.update && scope.kind === "all" ? { counts: {} } : readBaseline(baselineFile);
327
+ if ("error" in baseline) {
328
+ options.log(`trust baseline: could not read the baseline: ${baseline.error}`);
329
+ return 2;
330
+ }
331
+ if (options.update) {
332
+ const updated = updateBaseline(baseline.counts, findings, scope);
333
+ writeFileSync(baselineFile, serializeBaseline(updated.counts));
334
+ const kept = updated.kept > 0 ? ` Kept the entries of ${updated.kept} unchecked file(s).` : "";
335
+ options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${files.length} checked file(s).${kept}`);
336
+ return 0;
337
+ }
338
+ const { added, stale } = compareToBaseline(findings, baseline.counts, scope);
339
+ if (stale.length > 0) {
340
+ options.log(`${stale.length} baseline entr${stale.length === 1 ? "y has" : "ies have"} fewer findings now; run with --update to shrink the baseline.`);
341
+ }
342
+ if (added.length === 0) {
343
+ options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${files.length} file(s)).`);
344
+ return 0;
345
+ }
346
+ const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);
347
+ options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);
348
+ for (const delta of added) for (const line of describeBaselineDelta(delta)) options.log(` ${line}`);
349
+ options.log("Guard each call (try/catch returning Result.err, or Trust.try), or trust its origin in trust.config.json.");
350
+ const hasTypeClaims = added.some((delta) => delta.rule === TYPE_CLAIM_RULE);
351
+ if (hasTypeClaims) options.log("Prove each claimed type (narrow or validate the value) instead of asserting it.");
352
+ const hasUntrustedValues = added.some((delta) => delta.rule === UNTRUSTED_VALUE_RULE);
353
+ if (hasUntrustedValues) {
354
+ 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.');
355
+ }
356
+ if (added.some((delta) => delta.rule === DROPPED_RESULT_RULE)) {
357
+ options.log("Return each dropped failure (`if (!r.ok) return r;`) or handle it with Trust.decide.");
358
+ }
359
+ if (added.some((delta) => delta.rule === BOUNDARY_RULE)) {
360
+ options.log('Decide every kind at each boundary (an exhaustive `switch`) and return plain data, or exclude it under "boundaries" in trust.config.json.');
361
+ }
362
+ const alsoShows = `${hasTypeClaims ? ", and why a line is a type claim" : ""}${hasUntrustedValues ? ", and where an untrusted value comes from" : ""}`;
363
+ options.log(`\`trust explain <file>:<line>\` shows which origin a call resolves to${alsoShows}.`);
364
+ return 1;
365
+ }
366
+
372
367
  // src/cli/check-command.ts
368
+ import { existsSync as existsSync2 } from "fs";
369
+ import { resolve as resolve4 } from "path";
373
370
  async function runCheckCommand(options) {
374
371
  const fail = (errors) => {
375
372
  if (options.json) options.log(JSON.stringify({ findings: [], errors, warnings: [] }));
@@ -422,6 +419,116 @@ async function runCheckCommand(options) {
422
419
  }
423
420
  }
424
421
 
422
+ // src/cli/run-lock.ts
423
+ import { closeSync, mkdirSync, openSync, rmSync, statSync as statSync2 } from "fs";
424
+ import { createHash } from "crypto";
425
+ import { createConnection, createServer } from "net";
426
+ import { tmpdir } from "os";
427
+ import { join as join3 } from "path";
428
+ function runLockDirectory(env = process.env) {
429
+ return env.TRUST_RUNTIME_DIR || join3(tmpdir(), "noego-trust");
430
+ }
431
+ function runLockDisabled(env = process.env) {
432
+ return env.TRUST_RUN_LOCK === "0";
433
+ }
434
+ function runLockSocketPath(directory, platform = process.platform) {
435
+ if (platform !== "win32") return join3(directory, "run.sock");
436
+ const hash = createHash("sha256").update(directory).digest("hex").slice(0, 16);
437
+ return `\\\\.\\pipe\\noego-trust-${hash}-run`;
438
+ }
439
+ function errnoCode(error) {
440
+ return error?.code;
441
+ }
442
+ function listen(socketPath) {
443
+ return new Promise((resolve7, reject) => {
444
+ const server = createServer();
445
+ server.once("error", (error) => {
446
+ const code = errnoCode(error);
447
+ if (code === "EADDRINUSE" || code === "EEXIST") resolve7({ kind: "in-use" });
448
+ else reject(error);
449
+ });
450
+ server.listen(socketPath, () => resolve7({ kind: "held", server }));
451
+ });
452
+ }
453
+ function probe(socketPath) {
454
+ return new Promise((resolve7, reject) => {
455
+ const socket = createConnection(socketPath);
456
+ socket.once("connect", () => resolve7({ kind: "alive", socket }));
457
+ socket.once("error", (error) => {
458
+ const code = errnoCode(error);
459
+ if (code === "ECONNREFUSED" || code === "ENOENT" || code === "ENOTSOCK") resolve7({ kind: "dead" });
460
+ else reject(error);
461
+ });
462
+ });
463
+ }
464
+ function waitForClose(socket) {
465
+ return new Promise((resolve7) => {
466
+ socket.once("close", () => resolve7());
467
+ socket.on("error", () => void 0);
468
+ socket.on("data", () => void 0);
469
+ });
470
+ }
471
+ function reclaim(directory, socketPath, staleMs) {
472
+ const guard = join3(directory, "reclaim.lock");
473
+ try {
474
+ closeSync(openSync(guard, "wx"));
475
+ } catch (error) {
476
+ if (errnoCode(error) !== "EEXIST") throw error;
477
+ try {
478
+ if (Date.now() - statSync2(guard).mtimeMs < staleMs) return false;
479
+ } catch {
480
+ return false;
481
+ }
482
+ rmSync(guard, { force: true });
483
+ return false;
484
+ }
485
+ try {
486
+ rmSync(socketPath, { force: true });
487
+ } finally {
488
+ rmSync(guard, { force: true });
489
+ }
490
+ return true;
491
+ }
492
+ async function acquireRunLock(options = {}) {
493
+ const directory = options.directory ?? runLockDirectory();
494
+ const reclaimStaleMs = options.reclaimStaleMs ?? 1e4;
495
+ mkdirSync(directory, { recursive: true });
496
+ const socketPath = runLockSocketPath(directory);
497
+ let announced = false;
498
+ for (; ; ) {
499
+ const listened = await listen(socketPath);
500
+ if (listened.kind === "held") return holdLock(listened.server, socketPath);
501
+ const probed = await probe(socketPath);
502
+ if (probed.kind === "dead") {
503
+ if (!reclaim(directory, socketPath, reclaimStaleMs)) await new Promise((done) => setTimeout(done, 50));
504
+ continue;
505
+ }
506
+ if (!announced) {
507
+ announced = true;
508
+ options.onWait?.();
509
+ }
510
+ await waitForClose(probed.socket);
511
+ }
512
+ }
513
+ function holdLock(server, socketPath) {
514
+ const waiters = /* @__PURE__ */ new Set();
515
+ server.on("connection", (socket) => {
516
+ waiters.add(socket);
517
+ socket.on("error", () => void 0);
518
+ socket.once("close", () => waiters.delete(socket));
519
+ });
520
+ server.unref();
521
+ let released;
522
+ const release = () => {
523
+ released ??= new Promise((resolve7) => {
524
+ server.close(() => resolve7());
525
+ for (const socket of waiters) socket.destroy();
526
+ });
527
+ return released;
528
+ };
529
+ return { path: socketPath, release };
530
+ }
531
+
425
532
  // src/cli/explain.ts
426
533
  import { resolve as resolve5 } from "path";
427
534
  function clipText(raw) {
@@ -540,7 +647,7 @@ function explain(options) {
540
647
  function describeBoundary(boundary) {
541
648
  const lines = [` boundary: ${boundary.member} (${boundary.item}, rule ${BOUNDARY_RULE})`];
542
649
  const { verdict } = boundary;
543
- const returns = verdict.kind === "plain" ? "plain data: nothing reported" : verdict.kind === "result" ? `a Result that can fail with ${formatFailureKinds(verdict.kinds, ANY_KIND)}` : `\`${verdict.type}\`, which may hold a Result`;
650
+ const returns = verdict.kind === "plain" ? "plain data: nothing reported" : verdict.kind === "result" ? verdict.kinds.length === 0 ? "a Result object that cannot fail" : `a Result that can fail with ${formatFailureKinds(verdict.kinds, ANY_KIND)}` : `\`${verdict.type}\`, which may hold a Result`;
544
651
  if (boundary.excludedBy) lines.push(` returns: ${returns}`, ` excluded: by "${boundary.excludedBy}" in the item's "exclude": nothing reported`);
545
652
  else if (boundary.reported) lines.push(` returns: ${returns}: reported as ${boundary.reported === "warning" ? "a warning (an error where strict applies)" : "an error"}`);
546
653
  else lines.push(` returns: ${returns}`);
@@ -657,7 +764,7 @@ function formatExplanation(explanation) {
657
764
 
658
765
  // src/cli/refactor-command.ts
659
766
  import { existsSync as existsSync3 } from "fs";
660
- import { join as join3, resolve as resolve6 } from "path";
767
+ import { join as join4, resolve as resolve6 } from "path";
661
768
 
662
769
  // src/core/call-graph.ts
663
770
  var TOP_LEVEL = "(top level)";
@@ -1327,7 +1434,7 @@ async function runRefactorCommand(options) {
1327
1434
  logUnmatchedGlobs(options.log, "refactor", config);
1328
1435
  const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
1329
1436
  const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
1330
- const baselineFile = resolve6(options.cwd, options.baselineFile ?? join3(config.rootDir, "trust-baseline.json"));
1437
+ const baselineFile = resolve6(options.cwd, options.baselineFile ?? join4(config.rootDir, "trust-baseline.json"));
1331
1438
  const fromBaseline = existsSync3(baselineFile);
1332
1439
  if (!fromBaseline && options.baselineFile !== void 0) {
1333
1440
  options.log(`trust refactor: no such baseline: ${options.baselineFile}`);
@@ -1577,7 +1684,20 @@ async function main(argv) {
1577
1684
  throw new Error(`unknown command "${command}"
1578
1685
  ${USAGE}`);
1579
1686
  }
1580
- main(process.argv.slice(2)).then(
1687
+ var HEAVY_COMMANDS = /* @__PURE__ */ new Set(["baseline", "check", "refactor"]);
1688
+ async function runExclusive(argv) {
1689
+ const [command] = argv;
1690
+ if (!command || !HEAVY_COMMANDS.has(command) || argv.includes("--help") || runLockDisabled()) return main(argv);
1691
+ const lock = await acquireRunLock({
1692
+ onWait: () => console.error("trust: another trust run is in progress on this machine; waiting for it to finish\u2026")
1693
+ });
1694
+ try {
1695
+ return await main(argv);
1696
+ } finally {
1697
+ await lock.release();
1698
+ }
1699
+ }
1700
+ runExclusive(process.argv.slice(2)).then(
1581
1701
  (code) => {
1582
1702
  process.exitCode = code;
1583
1703
  },