@ttsc/lint 0.20.1 → 0.22.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/lib/index.js CHANGED
@@ -17,7 +17,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.TTSX_EXTRACTOR_SCRIPT = void 0;
20
21
  exports.default = createTtscPlugin;
22
+ const node_buffer_1 = require("node:buffer");
21
23
  const node_child_process_1 = require("node:child_process");
22
24
  const node_crypto_1 = require("node:crypto");
23
25
  const node_fs_1 = __importDefault(require("node:fs"));
@@ -101,6 +103,9 @@ function createTtscPlugin(context) {
101
103
  diagnosticsTiming: true,
102
104
  lsp: true,
103
105
  projectContextArgs: true,
106
+ projectDiagnostics: true,
107
+ projectInputs: true,
108
+ residentCheck: true,
104
109
  threadingArgs: true,
105
110
  },
106
111
  name: "@ttsc/lint",
@@ -319,56 +324,56 @@ function tsconfigBaseDir(context) {
319
324
  return node_path_1.default.resolve(cwd);
320
325
  }
321
326
  function readConfigPluginEntries(configPath, context) {
322
- const ext = node_path_1.default.extname(configPath).toLowerCase();
323
- if (ext === ".json") {
324
- return readJsonConfigPlugins(configPath, context);
325
- }
326
- if (ext === ".js" || ext === ".cjs") {
327
- return readCjsConfigPlugins(configPath);
328
- }
329
- // .ts, .cts, .mts, .mjs all need ttsx-side evaluation. .mjs sneaks in
330
- // here because Node can't `require()` an ESM file synchronously.
327
+ // A JSON config that can bring no contributor with it — no `plugins` map and
328
+ // no `extends` chain to follow — has nothing to extract, and reading it runs
329
+ // no user code, so the isolated evaluator is not needed to keep its strings
330
+ // away from stdout. Skipping it there matters beyond the cost: the evaluator
331
+ // is a real subprocess, and a host that only wanted to know whether there
332
+ // were contributors would otherwise depend on a launcher being resolvable and
333
+ // on a compiler accepting one more invocation.
334
+ if (jsonConfigDeclaresNoContributor(configPath))
335
+ return [];
336
+ // Every other config uses the same isolated evaluator. Executable config can
337
+ // name contributor packages whose top-level code writes to stdout, so loading
338
+ // it in this host process would corrupt CLI JSON or preface the first LSP
339
+ // frame.
331
340
  return readTtsxConfigPlugins(configPath, context);
332
341
  }
333
- function readJsonConfigPlugins(configPath, context) {
334
- let parsed;
342
+ function jsonConfigDeclaresNoContributor(configPath) {
343
+ if (node_path_1.default.extname(configPath).toLowerCase() !== ".json")
344
+ return false;
335
345
  try {
336
- // Strip a leading UTF-8 BOM so files saved by Windows editors
337
- // (Notepad++, some VS Code setups) round-trip through `JSON.parse`
338
- // without an opaque "Unexpected token" failure.
339
- const text = node_fs_1.default.readFileSync(configPath, "utf8").replace(/^\uFEFF/, "");
340
- parsed = JSON.parse(text);
346
+ const value = JSON.parse(node_fs_1.default.readFileSync(configPath, "utf8"));
347
+ return !configMayDeclareContributor(value);
341
348
  }
342
- catch (error) {
343
- throw new Error(`@ttsc/lint: failed to parse lint config ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
349
+ catch {
350
+ // A malformed config is the evaluator's diagnostic to report, not this
351
+ // shortcut's, so it falls through to the path that reports it.
352
+ return false;
344
353
  }
345
- // In JSON, plugin values can only be strings (npm specifiers) — there
346
- // is no way to attach an in-memory plugin object inside a JSON file.
347
- return collectPluginObjectsFromConfig(parsed)
348
- .flatMap((map) => Object.entries(map))
349
- .map(([namespace, value]) => {
350
- if (!NAMESPACE_PATTERN.test(namespace)) {
351
- throw new Error(`@ttsc/lint: lint config ${configPath} namespace ${JSON.stringify(namespace)} must match /^[a-z][a-z0-9_-]*$/`);
352
- }
353
- if (typeof value !== "string" || value.length === 0) {
354
- throw new Error(`@ttsc/lint: lint config ${configPath} plugin ${JSON.stringify(namespace)} must point at a package specifier string`);
355
- }
356
- const plugin = loadContributorPluginViaRequire(value, context, namespace, configPath);
357
- return { namespace, source: plugin.source };
358
- });
359
354
  }
360
- function readCjsConfigPlugins(configPath) {
361
- let mod;
362
- try {
363
- const requireFromConfig = (0, node_module_1.createRequire)(configPath);
364
- mod = requireFromConfig(configPath);
355
+ /**
356
+ * Whether any object in a config could still bring a contributor with it.
357
+ *
358
+ * A `plugins` map names one directly. An `extends` chain names one indirectly:
359
+ * the base it points at may be executable and may declare contributors of its
360
+ * own, and following that chain is the evaluator's job. Treating a config that
361
+ * extends anything as undecidable here is what keeps this shortcut from
362
+ * silently dropping a contributor the base would have supplied.
363
+ */
364
+ function configMayDeclareContributor(value) {
365
+ if (Array.isArray(value)) {
366
+ return value.some((entry) => configMayDeclareContributor(entry));
365
367
  }
366
- catch (error) {
367
- throw new Error(`@ttsc/lint: failed to load lint config ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
368
+ if (value === null || typeof value !== "object")
369
+ return false;
370
+ const record = value;
371
+ for (const key of ["plugins", "extends"]) {
372
+ const declared = record[key];
373
+ if (declared !== undefined && declared !== null)
374
+ return true;
368
375
  }
369
- return collectPluginObjectsFromConfig(unwrapDefault(mod))
370
- .flatMap((map) => Object.entries(map))
371
- .map(([namespace, value]) => normalizePluginValue(namespace, value, configPath));
376
+ return false;
372
377
  }
373
378
  // TypeScript source written to a temp file and executed via ttsx. The
374
379
  // %CONFIG_IMPORT% placeholder is replaced with a JSON-quoted file URL
@@ -377,7 +382,30 @@ function readCjsConfigPlugins(configPath) {
377
382
  // as a JSON array for the parent process to parse — avoiding the need to
378
383
  // serialise arbitrary in-memory plugin objects across the process boundary.
379
384
  // The URL lives in a variable so tsgo does not statically resolve it.
380
- const TTSX_EXTRACTOR_SCRIPT = `const configUrl = %CONFIG_IMPORT%;
385
+ /**
386
+ * The descriptor extractor's emitted source.
387
+ *
388
+ * Exported so a regression can inspect the same bytes the loader executes. The
389
+ * template consumes its own escapes, so reading this file's text instead would
390
+ * check characters no consumer ever sees.
391
+ */
392
+ exports.TTSX_EXTRACTOR_SCRIPT = `// @ts-ignore -- internal loader must not require user-installed Node typings.
393
+ import * as fs from "node:fs";
394
+ // @ts-ignore -- internal loader must not require user-installed Node typings.
395
+ import { Buffer } from "node:buffer";
396
+ // @ts-ignore -- internal loader must not require user-installed Node typings.
397
+ import { createHash } from "node:crypto";
398
+ // @ts-ignore -- internal loader must not require user-installed Node typings.
399
+ import { createRequire, registerHooks } from "node:module";
400
+ // @ts-ignore -- internal loader must not require user-installed Node typings.
401
+ import * as path from "node:path";
402
+ // @ts-ignore -- internal loader must not require user-installed Node typings.
403
+ import { fileURLToPath, pathToFileURL } from "node:url";
404
+
405
+ const configUrl = %CONFIG_IMPORT%;
406
+ const outputPath = %CONFIG_OUTPUT%;
407
+ const resolutionRoot = path.resolve(%CONFIG_ROOT%);
408
+ const requireFromConfig = createRequire(configUrl);
381
409
  const CONFIG_KEYS = new Set<string>([
382
410
  "files",
383
411
  "ignores",
@@ -386,36 +414,969 @@ const CONFIG_KEYS = new Set<string>([
386
414
  "rules",
387
415
  "format",
388
416
  ]);
389
- const importedConfig = await import(configUrl);
417
+ const dependencies = new Map<string, {
418
+ digest: string;
419
+ kind: "directory" | "file" | "optional-file";
420
+ path: string;
421
+ owners: Set<string>;
422
+ }>();
423
+ const graphNodes = new Map<string, string>();
424
+ const graphEdges: Array<{
425
+ child: string;
426
+ packageBoundary: boolean;
427
+ parent: string;
428
+ }> = [];
429
+ const configLocation = fileURLToPath(configUrl);
430
+ // Every spelling of this config the module system might key an edge under.
431
+ //
432
+ // Which one it uses is not knowable from here, and guessing has failed in both
433
+ // directions. A path handed in by another producer can be escaped by a rule
434
+ // Node does not share. Node respells a resolved file module through its real
435
+ // path unless "--preserve-symlinks" is set, so a config reached through a
436
+ // symlinked directory is keyed by its target. And a Windows 8.3 short name is
437
+ // not a symlink: fs.realpathSync expands it, the module resolver does not, so
438
+ // asking the volume there produces a spelling no edge carries.
439
+ //
440
+ // A seed that names a URL no edge was keyed under sits on a node with no
441
+ // outgoing edges, the walk ends immediately, and every dependency recorded
442
+ // after the first import is demoted from watch to cache. That failure is
443
+ // silent: the build still succeeds and simply stops reacting. Seeding every
444
+ // spelling costs one extra queue entry and cannot be wrong.
445
+ const configUrlSpellings = [
446
+ ...new Set([
447
+ configUrl,
448
+ pathToFileURL(configLocation).href,
449
+ pathToFileURL(realConfigLocation()).href,
450
+ ]),
451
+ ];
452
+ for (const spelling of configUrlSpellings) {
453
+ graphNodes.set(spelling, configLocation);
454
+ }
455
+ recordDependency(
456
+ "file",
457
+ configLocation,
458
+ createHash("sha256").update(fs.readFileSync(configLocation)).digest("hex"),
459
+ configUrlSpellings,
460
+ );
461
+ recordPackageManifests(configLocation, configUrlSpellings);
390
462
 
391
463
  declare const process: {
392
464
  cwd(): string;
465
+ platform: string;
393
466
  stdout: { write(value: string): void };
394
467
  stderr: { write(value: string): void };
395
468
  exit(code?: number): never;
396
469
  };
397
470
 
471
+ const hooks = registerHooks({
472
+ resolve(specifier, context, nextResolve) {
473
+ const resolved = nextResolve(specifier, context);
474
+ if (typeof resolved.url !== "string" || !resolved.url.startsWith("file:")) {
475
+ return resolved;
476
+ }
477
+ const url = new URL(resolved.url).href;
478
+ const parent = context.parentURL && new URL(context.parentURL).href;
479
+ const location = fileURLToPath(url);
480
+ // The entry is recognized by what was asked for, not only by what came
481
+ // back. A module URL is assigned by whoever loaded it: a compiling loader
482
+ // can serve the config from its emitted output, and a platform can hand
483
+ // back a different spelling of the same file. Either way the URL bears no
484
+ // resemblance to the one this process was given, so the config's own
485
+ // imports would be rejected here — their parent is a URL no node was
486
+ // recorded under — and the graph would collapse to the records made before
487
+ // the first import. The request itself is unambiguous, so it decides.
488
+ const entry =
489
+ specifier === configUrl ||
490
+ url === new URL(configUrl).href ||
491
+ samePhysicalPath(location, configLocation);
492
+ if (!entry && (parent === undefined || !graphNodes.has(parent))) {
493
+ return resolved;
494
+ }
495
+ graphNodes.set(url, location);
496
+ if (parent !== undefined) {
497
+ graphEdges.push({
498
+ child: url,
499
+ packageBoundary:
500
+ pathHasNodeModules(location) && !isLocalModuleSpecifier(specifier),
501
+ parent,
502
+ });
503
+ recordResolutionTopology(
504
+ specifier,
505
+ parent,
506
+ url,
507
+ location,
508
+ context.conditions,
509
+ );
510
+ }
511
+ try {
512
+ recordDependency(
513
+ "file",
514
+ location,
515
+ createHash("sha256").update(fs.readFileSync(location)).digest("hex"),
516
+ [url],
517
+ );
518
+ } catch {
519
+ // The evaluator remains authoritative for the load error. An unreadable
520
+ // dependency simply makes this result non-cacheable in the parent.
521
+ recordDependency("file", location, "", [url]);
522
+ }
523
+ return resolved;
524
+ },
525
+ });
526
+
398
527
  try {
528
+ const importedConfig = configLocation.toLowerCase().endsWith(".json")
529
+ ? JSON.parse(fs.readFileSync(configLocation, "utf8").replace(/^\uFEFF/, ""))
530
+ : await import(configUrl);
399
531
  const current = await resolveConfig(importedConfig, true);
400
532
  const pluginMaps = collectPluginObjects(current);
401
533
  const entries: Array<{ namespace: string; source: string }> = [];
402
534
  for (const map of pluginMaps) {
403
535
  for (const [namespace, value] of Object.entries(map)) {
404
536
  const source = extractPluginSource(value);
405
- if (source === undefined) continue;
537
+ if (source === undefined || source.length === 0) {
538
+ throw new Error(
539
+ \`contributor \${JSON.stringify(namespace)} must resolve to an object with a non-empty "source" string\`,
540
+ );
541
+ }
406
542
  entries.push({ namespace, source });
407
543
  }
408
544
  }
409
- process.stdout.write(JSON.stringify({ entries }));
545
+ fs.writeFileSync(outputPath, JSON.stringify({
546
+ dependencies: finalizeDependencies(),
547
+ entries,
548
+ }), "utf8");
410
549
  } catch (error) {
411
550
  process.stderr.write(error instanceof Error && error.stack ? error.stack : String(error));
412
551
  process.exit(1);
552
+ } finally {
553
+ hooks.deregister();
413
554
  }
414
555
 
415
556
  function isObject(value: unknown): value is Record<string, unknown> {
416
557
  return value !== null && typeof value === "object";
417
558
  }
418
559
 
560
+ function recordDependency(
561
+ kind: "directory" | "file" | "optional-file",
562
+ location: string,
563
+ digest: string,
564
+ owners: readonly string[],
565
+ ): void {
566
+ const key = kind + "\\0" + location;
567
+ const previous = dependencies.get(key);
568
+ const mergedOwners = previous?.owners ?? new Set<string>();
569
+ for (const owner of owners) mergedOwners.add(owner);
570
+ dependencies.set(key, {
571
+ digest: previous !== undefined && previous.digest !== digest ? "" : digest,
572
+ kind,
573
+ owners: mergedOwners,
574
+ path: location,
575
+ });
576
+ }
577
+
578
+ function isLocalModuleSpecifier(specifier: string): boolean {
579
+ return specifier.startsWith(".") ||
580
+ specifier.startsWith("/") ||
581
+ specifier.startsWith("file:") ||
582
+ /^[A-Za-z]:[\\\\/]/.test(specifier);
583
+ }
584
+
585
+ function pathHasNodeModules(location: string): boolean {
586
+ return location.replaceAll("\\\\", "/").split("/").includes("node_modules");
587
+ }
588
+
589
+ function recordResolutionTopology(
590
+ specifier: string,
591
+ parentUrl: string,
592
+ childUrl: string,
593
+ childLocation: string,
594
+ conditions: readonly string[],
595
+ ): void {
596
+ const owners = [parentUrl, childUrl];
597
+ const parentLocation = graphNodes.get(parentUrl);
598
+ if (parentLocation !== undefined && isLocalModuleSpecifier(specifier)) {
599
+ recordDirectoryDependency(path.dirname(parentLocation), owners);
600
+ }
601
+ recordDirectoryDependency(path.dirname(childLocation), owners);
602
+ recordPackageManifests(childLocation, owners);
603
+ if (parentLocation !== undefined && !isLocalModuleSpecifier(specifier)) {
604
+ recordNodeModulesSearchDirectories(
605
+ parentLocation,
606
+ specifier,
607
+ childLocation,
608
+ owners,
609
+ conditions,
610
+ );
611
+ }
612
+ }
613
+
614
+ function recordDirectoryDependency(
615
+ location: string,
616
+ owners: readonly string[],
617
+ ): void {
618
+ try {
619
+ recordDependency("directory", location, directoryDigest(location), owners);
620
+ } catch {
621
+ recordDependency("directory", location, "", owners);
622
+ }
623
+ }
624
+
625
+ function directoryDigest(location: string): string {
626
+ const entries: Buffer[] = [];
627
+ if (process.platform === "win32") {
628
+ for (const entry of fs.readdirSync(location, { withFileTypes: true })) {
629
+ let target = Buffer.alloc(0);
630
+ if (entry.isSymbolicLink()) {
631
+ try {
632
+ target = Buffer.from(
633
+ fs.readlinkSync(path.join(location, entry.name)),
634
+ "utf8",
635
+ );
636
+ } catch {
637
+ target = Buffer.from("<unreadable>");
638
+ }
639
+ }
640
+ entries.push(directoryDigestRecord(Buffer.from(entry.name), entry, target));
641
+ }
642
+ } else {
643
+ for (const entry of fs.readdirSync(location, {
644
+ encoding: "buffer",
645
+ withFileTypes: true,
646
+ })) {
647
+ let target = Buffer.alloc(0);
648
+ if (entry.isSymbolicLink()) {
649
+ try {
650
+ target = fs.readlinkSync(
651
+ Buffer.concat([
652
+ Buffer.from(location),
653
+ Buffer.from(path.sep),
654
+ entry.name,
655
+ ]),
656
+ { encoding: "buffer" },
657
+ );
658
+ } catch {
659
+ target = Buffer.from("<unreadable>");
660
+ }
661
+ }
662
+ entries.push(directoryDigestRecord(entry.name, entry, target));
663
+ }
664
+ }
665
+ entries.sort(Buffer.compare);
666
+ const serialized = Buffer.concat(
667
+ entries.flatMap((entry, index) =>
668
+ index === 0 ? [entry] : [Buffer.from([0]), entry],
669
+ ),
670
+ );
671
+ return createHash("sha256").update(serialized).digest("hex");
672
+ }
673
+
674
+ function directoryDigestRecord(
675
+ name: Buffer,
676
+ entry: {
677
+ isDirectory(): boolean;
678
+ isFile(): boolean;
679
+ isSymbolicLink(): boolean;
680
+ },
681
+ target: Buffer,
682
+ ): Buffer {
683
+ const kind = entry.isDirectory()
684
+ ? "directory"
685
+ : entry.isFile()
686
+ ? "file"
687
+ : entry.isSymbolicLink()
688
+ ? "symlink"
689
+ : "other";
690
+ return Buffer.concat([name, Buffer.from("\\0" + kind + "\\0"), target]);
691
+ }
692
+
693
+ function optionalFileDigest(location: string): string {
694
+ try {
695
+ if (fs.statSync(location).isFile()) {
696
+ return createHash("sha256")
697
+ .update(Buffer.concat([Buffer.from("file\\0"), fs.readFileSync(location)]))
698
+ .digest("hex");
699
+ }
700
+ } catch {
701
+ // Missing, unreadable, and non-file candidates share the absent state.
702
+ }
703
+ return createHash("sha256").update("missing\\0").digest("hex");
704
+ }
705
+
706
+ function recordOptionalFileDependency(
707
+ location: string,
708
+ owners: readonly string[],
709
+ ): boolean {
710
+ try {
711
+ if (fs.statSync(location).isFile()) {
712
+ recordDependency(
713
+ "file",
714
+ location,
715
+ createHash("sha256").update(fs.readFileSync(location)).digest("hex"),
716
+ owners,
717
+ );
718
+ return true;
719
+ }
720
+ } catch {
721
+ // The exact missing path remains a dependency of the resolution result.
722
+ }
723
+ recordDependency("optional-file", location, optionalFileDigest(location), owners);
724
+ return false;
725
+ }
726
+
727
+ function recordPackageManifests(
728
+ location: string,
729
+ owners: readonly string[],
730
+ ): void {
731
+ let current = path.dirname(location);
732
+ while (true) {
733
+ const manifest = path.join(current, "package.json");
734
+ if (recordOptionalFileDependency(manifest, owners)) return;
735
+ const parent = path.dirname(current);
736
+ if (parent === current || path.basename(current) === "node_modules") return;
737
+ current = parent;
738
+ }
739
+ }
740
+
741
+ function recordNodeModulesSearchDirectories(
742
+ parentLocation: string,
743
+ specifier: string,
744
+ childLocation: string,
745
+ owners: readonly string[],
746
+ conditions: readonly string[],
747
+ ): void {
748
+ const packageName = modulePackageName(specifier);
749
+ const scope =
750
+ specifier.startsWith("@") && specifier.includes("/")
751
+ ? specifier.slice(0, specifier.indexOf("/"))
752
+ : undefined;
753
+ let current = path.dirname(parentLocation);
754
+ while (true) {
755
+ // A newly created nearer node_modules directory can shadow the package
756
+ // selected by this evaluation, so missing search levels are dependencies.
757
+ recordDirectoryDependency(current, owners);
758
+ const modules = path.join(current, "node_modules");
759
+ try {
760
+ if (fs.statSync(modules).isDirectory()) {
761
+ recordDirectoryDependency(modules, owners);
762
+ if (scope !== undefined) {
763
+ const scoped = path.join(modules, scope);
764
+ try {
765
+ if (fs.statSync(scoped).isDirectory()) {
766
+ recordDirectoryDependency(scoped, owners);
767
+ }
768
+ } catch {
769
+ // The directory digest of node_modules records a missing scope.
770
+ }
771
+ }
772
+ if (packageName !== undefined) {
773
+ const selected = recordPackageCandidateTopology(
774
+ modules,
775
+ packageName,
776
+ specifier,
777
+ childLocation,
778
+ owners,
779
+ conditions,
780
+ );
781
+ if (
782
+ selected ||
783
+ resolvedPackageContains(modules, packageName, childLocation)
784
+ ) {
785
+ return;
786
+ }
787
+ }
788
+ }
789
+ } catch {
790
+ // Missing search levels do not participate in the current resolution.
791
+ }
792
+ if (
793
+ packageName === undefined &&
794
+ samePhysicalPath(current, resolutionRoot)
795
+ ) {
796
+ return;
797
+ }
798
+ const parent = path.dirname(current);
799
+ if (parent === current) return;
800
+ current = parent;
801
+ }
802
+ }
803
+
804
+ function recordPackageCandidateTopology(
805
+ modules: string,
806
+ packageName: string,
807
+ specifier: string,
808
+ childLocation: string,
809
+ owners: readonly string[],
810
+ conditions: readonly string[],
811
+ ): boolean {
812
+ const packageRoot = path.join(modules, packageName);
813
+ try {
814
+ if (!fs.statSync(packageRoot).isDirectory()) return false;
815
+ } catch {
816
+ return false;
817
+ }
818
+ const subpath = specifier
819
+ .slice(packageName.length)
820
+ .replace(/^[/\\\\]+/, "");
821
+ const rootTopology = recordPackageRootTopology(
822
+ packageRoot,
823
+ owners,
824
+ subpath === "",
825
+ subpath === "" ? "." : "./" + subpath.replaceAll("\\\\", "/"),
826
+ childLocation,
827
+ conditions,
828
+ );
829
+ if (subpath !== "" && !rootTopology.hasExports) {
830
+ return (
831
+ recordPackageSubpathTopology(
832
+ packageRoot,
833
+ subpath,
834
+ childLocation,
835
+ owners,
836
+ ) || rootTopology.selected
837
+ );
838
+ }
839
+ return rootTopology.selected;
840
+ }
841
+
842
+ function recordPackageRootTopology(
843
+ packageRoot: string,
844
+ owners: readonly string[],
845
+ useMain: boolean,
846
+ packageSubpath: string,
847
+ childLocation: string,
848
+ conditions: readonly string[],
849
+ ): { hasExports: boolean; selected: boolean } {
850
+ const normalizedRoot = path.resolve(packageRoot);
851
+ const manifest = path.join(normalizedRoot, "package.json");
852
+ const legacySelected = (): boolean =>
853
+ useMain &&
854
+ packagePathCandidateMatchesChild(normalizedRoot, childLocation, true);
855
+ if (!recordOptionalFileDependency(manifest, owners)) {
856
+ const selected = legacySelected();
857
+ if (!selected) {
858
+ recordPackageIndexCandidates(normalizedRoot, useMain, owners);
859
+ }
860
+ return { hasExports: false, selected };
861
+ }
862
+ try {
863
+ const value = JSON.parse(fs.readFileSync(manifest, "utf8"));
864
+ if (value !== null && typeof value === "object") {
865
+ const metadata = value as Record<string, unknown>;
866
+ const hasExports =
867
+ metadata.exports !== undefined && metadata.exports !== null;
868
+ if (hasExports) {
869
+ const target = selectPackageExportsTarget(
870
+ metadata.exports,
871
+ packageSubpath,
872
+ new Set(conditions),
873
+ );
874
+ const candidate =
875
+ typeof target === "string"
876
+ ? packageExportsTarget(normalizedRoot, target)
877
+ : undefined;
878
+ const selected =
879
+ candidate !== undefined &&
880
+ packagePathCandidateMatchesChild(
881
+ candidate,
882
+ childLocation,
883
+ false,
884
+ );
885
+ if (selected) {
886
+ recordPackagePathCandidate(candidate, owners);
887
+ } else if (candidate !== undefined) {
888
+ // A nearer package the search skipped starts winning the moment its
889
+ // own active target appears, and neither the parent node_modules
890
+ // listing nor the manifest changes when only that file is created.
891
+ recordOptionalFileDependency(candidate, owners);
892
+ }
893
+ return { hasExports: true, selected };
894
+ }
895
+ let selected = legacySelected();
896
+ if (useMain && typeof metadata.main === "string") {
897
+ // CommonJS main is a legacy path, not an exports target. Node resolves
898
+ // it literally and permits absolute paths and paths outside the package.
899
+ const main = path.resolve(normalizedRoot, metadata.main);
900
+ recordPackagePathCandidate(main, owners);
901
+ selected =
902
+ packagePathCandidateMatchesChild(main, childLocation, true) ||
903
+ selected;
904
+ }
905
+ if (!selected) {
906
+ recordPackageIndexCandidates(normalizedRoot, useMain, owners);
907
+ }
908
+ return {
909
+ hasExports: false,
910
+ selected,
911
+ };
912
+ }
913
+ } catch {
914
+ // Node owns malformed-manifest diagnostics; the manifest digest is enough
915
+ // to invalidate this evaluation when its contents change.
916
+ }
917
+ const selected = legacySelected();
918
+ if (!selected) {
919
+ recordPackageIndexCandidates(normalizedRoot, useMain, owners);
920
+ }
921
+ return { hasExports: false, selected };
922
+ }
923
+
924
+ // recordPackageIndexCandidates pins the LOAD_INDEX fallbacks of a package root
925
+ // this resolution walked past without selecting. An empty package directory, or
926
+ // one whose manifest declares no usable entry, becomes resolvable as soon as one
927
+ // of these files exists, and that creation changes neither the parent directory
928
+ // listing nor the manifest digest already recorded for the candidate.
929
+ function recordPackageIndexCandidates(
930
+ packageRoot: string,
931
+ useMain: boolean,
932
+ owners: readonly string[],
933
+ ): void {
934
+ if (!useMain) return;
935
+ for (const name of ["index.js", "index.json", "index.node"]) {
936
+ recordOptionalFileDependency(path.join(packageRoot, name), owners);
937
+ }
938
+ }
939
+
940
+ function selectPackageExportsTarget(
941
+ exportsValue: unknown,
942
+ packageSubpath: string,
943
+ conditions: ReadonlySet<string>,
944
+ ): string | null | undefined {
945
+ let mappings: unknown = exportsValue;
946
+ if (
947
+ typeof mappings === "string" ||
948
+ Array.isArray(mappings) ||
949
+ (isObject(mappings) &&
950
+ Object.keys(mappings).every((key) => !key.startsWith(".")))
951
+ ) {
952
+ if (packageSubpath !== ".") return undefined;
953
+ return selectPackageTarget(mappings, "", false, conditions);
954
+ }
955
+ if (!isObject(mappings)) return undefined;
956
+ if (
957
+ Object.prototype.hasOwnProperty.call(mappings, packageSubpath) &&
958
+ !packageSubpath.includes("*") &&
959
+ !packageSubpath.endsWith("/")
960
+ ) {
961
+ return selectPackageTarget(
962
+ mappings[packageSubpath],
963
+ "",
964
+ false,
965
+ conditions,
966
+ );
967
+ }
968
+ let bestMatch = "";
969
+ let bestSubpath = "";
970
+ for (const key of Object.keys(mappings)) {
971
+ const wildcard = key.indexOf("*");
972
+ if (
973
+ wildcard === -1 ||
974
+ key.lastIndexOf("*") !== wildcard ||
975
+ !packageSubpath.startsWith(key.slice(0, wildcard))
976
+ ) {
977
+ continue;
978
+ }
979
+ const trailer = key.slice(wildcard + 1);
980
+ if (
981
+ packageSubpath.length < key.length ||
982
+ !packageSubpath.endsWith(trailer) ||
983
+ packagePatternKeyCompare(bestMatch, key) !== 1
984
+ ) {
985
+ continue;
986
+ }
987
+ bestMatch = key;
988
+ bestSubpath = packageSubpath.slice(
989
+ wildcard,
990
+ packageSubpath.length - trailer.length,
991
+ );
992
+ }
993
+ return bestMatch === ""
994
+ ? undefined
995
+ : selectPackageTarget(
996
+ mappings[bestMatch],
997
+ bestSubpath,
998
+ true,
999
+ conditions,
1000
+ );
1001
+ }
1002
+
1003
+ function selectPackageTarget(
1004
+ target: unknown,
1005
+ subpath: string,
1006
+ pattern: boolean,
1007
+ conditions: ReadonlySet<string>,
1008
+ ): string | null | undefined {
1009
+ if (typeof target === "string") {
1010
+ const selected = pattern ? target.replaceAll("*", subpath) : target;
1011
+ return validPackageExportsTarget(selected) ? selected : undefined;
1012
+ }
1013
+ if (Array.isArray(target)) {
1014
+ for (const item of target) {
1015
+ const selected = selectPackageTarget(
1016
+ item,
1017
+ subpath,
1018
+ pattern,
1019
+ conditions,
1020
+ );
1021
+ if (selected !== undefined && selected !== null) return selected;
1022
+ }
1023
+ return null;
1024
+ }
1025
+ if (isObject(target)) {
1026
+ for (const [condition, value] of Object.entries(target)) {
1027
+ if (condition !== "default" && !conditions.has(condition)) continue;
1028
+ const selected = selectPackageTarget(
1029
+ value,
1030
+ subpath,
1031
+ pattern,
1032
+ conditions,
1033
+ );
1034
+ if (selected !== undefined) return selected;
1035
+ }
1036
+ return undefined;
1037
+ }
1038
+ return target === null ? null : undefined;
1039
+ }
1040
+
1041
+ function packagePatternKeyCompare(left: string, right: string): number {
1042
+ const leftWildcard = left.indexOf("*");
1043
+ const rightWildcard = right.indexOf("*");
1044
+ const leftBase =
1045
+ leftWildcard === -1 ? left.length : leftWildcard + 1;
1046
+ const rightBase =
1047
+ rightWildcard === -1 ? right.length : rightWildcard + 1;
1048
+ if (leftBase > rightBase) return -1;
1049
+ if (rightBase > leftBase) return 1;
1050
+ if (leftWildcard === -1) return 1;
1051
+ if (rightWildcard === -1) return -1;
1052
+ if (left.length > right.length) return -1;
1053
+ if (right.length > left.length) return 1;
1054
+ return 0;
1055
+ }
1056
+
1057
+ function packageExportsTarget(
1058
+ packageRoot: string,
1059
+ target: string,
1060
+ ): string | undefined {
1061
+ if (!validPackageExportsTarget(target)) return undefined;
1062
+ try {
1063
+ // Node resolves an exports target as a URL against the package manifest,
1064
+ // so percent escapes, query strings, and fragments all take part in the
1065
+ // path it finally loads. Joining the raw target by hand diverges from that
1066
+ // whenever the target is anything but a plain relative path, and a target
1067
+ // Node resolves while this model rejects loses the selected file's
1068
+ // fingerprint, leaving a retargeted symlink cached as fresh.
1069
+ const packageUrl = pathToFileURL(path.join(packageRoot, "package.json"));
1070
+ const resolved = new URL(target, packageUrl);
1071
+ const packagePath = new URL(".", packageUrl).pathname;
1072
+ if (!resolved.pathname.startsWith(packagePath)) return undefined;
1073
+ return fileURLToPath(resolved);
1074
+ } catch {
1075
+ return undefined;
1076
+ }
1077
+ }
1078
+
1079
+ function validPackageExportsTarget(target: string): boolean {
1080
+ if (!target.startsWith("./") || /%2f|%5c/i.test(target)) return false;
1081
+ const components = target
1082
+ .slice(2)
1083
+ .replaceAll("\\\\", "/")
1084
+ .split("/");
1085
+ if (
1086
+ components.some(
1087
+ (component) => {
1088
+ try {
1089
+ const decoded = decodeURIComponent(component);
1090
+ return (
1091
+ decoded === "." ||
1092
+ decoded === ".." ||
1093
+ decoded.includes("/") ||
1094
+ decoded.includes("\\\\") ||
1095
+ decoded.toLowerCase() === "node_modules"
1096
+ );
1097
+ } catch {
1098
+ return true;
1099
+ }
1100
+ },
1101
+ )
1102
+ ) {
1103
+ return false;
1104
+ }
1105
+ return true;
1106
+ }
1107
+
1108
+ function packagePathCandidateMatchesChild(
1109
+ candidate: string,
1110
+ childLocation: string,
1111
+ legacy: boolean,
1112
+ ): boolean {
1113
+ let child: string;
1114
+ try {
1115
+ child = fs.realpathSync.native(childLocation);
1116
+ } catch {
1117
+ child = path.resolve(childLocation);
1118
+ }
1119
+ const candidates = legacy
1120
+ ? [
1121
+ candidate,
1122
+ candidate + ".js",
1123
+ candidate + ".json",
1124
+ candidate + ".node",
1125
+ path.join(candidate, "index.js"),
1126
+ path.join(candidate, "index.json"),
1127
+ path.join(candidate, "index.node"),
1128
+ ]
1129
+ : [candidate];
1130
+ return candidates.some((location) => {
1131
+ try {
1132
+ return sameResolutionPath(fs.realpathSync.native(location), child);
1133
+ } catch {
1134
+ return false;
1135
+ }
1136
+ });
1137
+ }
1138
+
1139
+ function recordPackageSubpathTopology(
1140
+ packageRoot: string,
1141
+ subpath: string,
1142
+ childLocation: string,
1143
+ owners: readonly string[],
1144
+ ): boolean {
1145
+ const candidate = boundedPackageTarget(packageRoot, subpath);
1146
+ if (candidate === undefined) return false;
1147
+ recordPackagePathCandidate(candidate, owners);
1148
+ let selected = packagePathCandidateMatchesChild(
1149
+ candidate,
1150
+ childLocation,
1151
+ true,
1152
+ );
1153
+ try {
1154
+ if (!fs.statSync(candidate).isDirectory()) return selected;
1155
+ } catch {
1156
+ return selected;
1157
+ }
1158
+ const manifest = path.join(candidate, "package.json");
1159
+ if (!recordOptionalFileDependency(manifest, owners)) return selected;
1160
+ try {
1161
+ const value = JSON.parse(fs.readFileSync(manifest, "utf8"));
1162
+ if (value !== null && typeof value === "object") {
1163
+ const metadata = value as Record<string, unknown>;
1164
+ if (typeof metadata.main === "string") {
1165
+ const main = path.resolve(candidate, metadata.main);
1166
+ recordPackagePathCandidate(main, owners);
1167
+ selected =
1168
+ packagePathCandidateMatchesChild(main, childLocation, true) ||
1169
+ selected;
1170
+ }
1171
+ }
1172
+ } catch {
1173
+ // Node owns malformed nested-package diagnostics.
1174
+ }
1175
+ return selected;
1176
+ }
1177
+
1178
+ function boundedPackageTarget(
1179
+ packageRoot: string,
1180
+ target: string,
1181
+ ): string | undefined {
1182
+ const candidate = path.resolve(packageRoot, target);
1183
+ const relative = path.relative(packageRoot, candidate);
1184
+ if (
1185
+ relative === ".." ||
1186
+ relative.startsWith(".." + path.sep) ||
1187
+ path.isAbsolute(relative)
1188
+ ) {
1189
+ return undefined;
1190
+ }
1191
+ return candidate;
1192
+ }
1193
+
1194
+ function recordPackagePathCandidate(
1195
+ candidate: string,
1196
+ owners: readonly string[],
1197
+ visited: Set<string> = new Set(),
1198
+ depth = 0,
1199
+ ): void {
1200
+ const normalized = path.resolve(candidate);
1201
+ // The depth bound owns termination. A platform-wide case fold would merge
1202
+ // paths that differ only by case, which a per-directory case-sensitive
1203
+ // Windows tree keeps distinct, and would truncate a valid symlink chain.
1204
+ if (depth >= 64 || visited.has(normalized)) return;
1205
+ visited.add(normalized);
1206
+ const parsed = path.parse(normalized);
1207
+ const components = normalized
1208
+ .slice(parsed.root.length)
1209
+ .split(path.sep)
1210
+ .filter(Boolean);
1211
+ let current = parsed.root;
1212
+ for (let index = 0; index < components.length; index++) {
1213
+ const component = components[index];
1214
+ const next = path.join(current, component);
1215
+ let entry: ReturnType<typeof fs.lstatSync>;
1216
+ try {
1217
+ entry = fs.lstatSync(next);
1218
+ } catch {
1219
+ recordDirectoryDependency(current, owners);
1220
+ return;
1221
+ }
1222
+ if (entry.isSymbolicLink()) {
1223
+ // The containing directory digest carries the raw link target.
1224
+ recordDirectoryDependency(current, owners);
1225
+ try {
1226
+ const target = fs.readlinkSync(next);
1227
+ const remainder = components.slice(index + 1);
1228
+ recordPackagePathCandidate(
1229
+ path.join(
1230
+ path.resolve(current, target),
1231
+ ...remainder,
1232
+ ),
1233
+ owners,
1234
+ visited,
1235
+ depth + 1,
1236
+ );
1237
+ } catch {
1238
+ // The lexical link record already carries the unreadable state.
1239
+ }
1240
+ }
1241
+ let isDirectory = entry.isDirectory();
1242
+ if (entry.isSymbolicLink()) {
1243
+ try {
1244
+ isDirectory = fs.statSync(next).isDirectory();
1245
+ } catch {
1246
+ return;
1247
+ }
1248
+ }
1249
+ if (index === components.length - 1) {
1250
+ recordDirectoryDependency(isDirectory ? next : current, owners);
1251
+ return;
1252
+ }
1253
+ if (!isDirectory) {
1254
+ recordDirectoryDependency(current, owners);
1255
+ return;
1256
+ }
1257
+ current = next;
1258
+ }
1259
+ recordDirectoryDependency(current, owners);
1260
+ }
1261
+
1262
+ function modulePackageName(specifier: string): string | undefined {
1263
+ if (specifier.startsWith("@")) {
1264
+ const components = specifier.split("/");
1265
+ return components.length >= 2
1266
+ ? components[0] + "/" + components[1]
1267
+ : undefined;
1268
+ }
1269
+ const [name] = specifier.split("/");
1270
+ return name && !name.startsWith("#") ? name : undefined;
1271
+ }
1272
+
1273
+ function resolvedPackageContains(
1274
+ modules: string,
1275
+ packageName: string,
1276
+ childLocation: string,
1277
+ ): boolean {
1278
+ try {
1279
+ const packageRoot = fs.realpathSync(path.join(modules, packageName));
1280
+ const relative = path.relative(
1281
+ packageRoot,
1282
+ fs.realpathSync(childLocation),
1283
+ );
1284
+ return (
1285
+ relative === "" ||
1286
+ (relative !== ".." &&
1287
+ !relative.startsWith(".." + path.sep) &&
1288
+ !path.isAbsolute(relative))
1289
+ );
1290
+ } catch {
1291
+ return false;
1292
+ }
1293
+ }
1294
+
1295
+ function sameResolutionPath(left: string, right: string): boolean {
1296
+ return path.relative(left, right) === "";
1297
+ }
1298
+
1299
+ function samePhysicalPath(left: string, right: string): boolean {
1300
+ try {
1301
+ return sameResolutionPath(realPath(left), realPath(right));
1302
+ } catch {
1303
+ // Fall back to the spellings themselves, folding case the way the platform
1304
+ // does. On the entry gate a false negative is catastrophic — the config
1305
+ // stops being recognized and its whole graph collapses — while a false
1306
+ // positive only over-includes, so the degradation has to lean toward "same
1307
+ // file". A drive-letter or component case difference is the ordinary
1308
+ // Windows situation; a per-directory case-sensitive tree is the rare one.
1309
+ return sameResolutionPath(left, right);
1310
+ }
1311
+ }
1312
+
1313
+ /**
1314
+ * The config's real path, or its declared one when the volume will not say.
1315
+ *
1316
+ * A config can disappear between the host reading it and this loader starting,
1317
+ * and a throw here would replace a precise report from the import below with a
1318
+ * crash in bookkeeping. Seeding lexically instead only risks the demotion this
1319
+ * value exists to prevent, on a file that is already gone.
1320
+ */
1321
+ function realConfigLocation(): string {
1322
+ try {
1323
+ return realPath(configLocation);
1324
+ } catch {
1325
+ return configLocation;
1326
+ }
1327
+ }
1328
+
1329
+ function realPath(location: string): string {
1330
+ return fs.realpathSync.native
1331
+ ? fs.realpathSync.native(location)
1332
+ : fs.realpathSync(location);
1333
+ }
1334
+
1335
+ function finalizeDependencies(): Array<{
1336
+ digest: string;
1337
+ kind: "directory" | "file" | "optional-file";
1338
+ path: string;
1339
+ scope: "cache" | "watch";
1340
+ }> {
1341
+ const watched = graphWatchReachability();
1342
+ return [...dependencies.values()].map(({ owners, ...dependency }) => ({
1343
+ ...dependency,
1344
+ scope: [...owners].some((owner) => watched.has(owner))
1345
+ ? "watch"
1346
+ : "cache",
1347
+ }));
1348
+ }
1349
+
1350
+ function graphWatchReachability(): Set<string> {
1351
+ const adjacency = new Map<string, typeof graphEdges>();
1352
+ for (const edge of graphEdges) {
1353
+ const outgoing = adjacency.get(edge.parent) ?? [];
1354
+ outgoing.push(edge);
1355
+ adjacency.set(edge.parent, outgoing);
1356
+ }
1357
+ const queue: Array<{ url: string; watched: boolean }> =
1358
+ configUrlSpellings.map((url) => ({ url, watched: true }));
1359
+ const visited = new Set<string>();
1360
+ const watched = new Set<string>();
1361
+ while (queue.length !== 0) {
1362
+ const state = queue.shift()!;
1363
+ const key = state.url + "\\0" + (state.watched ? "1" : "0");
1364
+ if (visited.has(key)) continue;
1365
+ visited.add(key);
1366
+ if (state.watched) watched.add(state.url);
1367
+ for (const edge of adjacency.get(state.url) ?? []) {
1368
+ const childLocation = graphNodes.get(edge.child);
1369
+ const childWatched = edge.packageBoundary
1370
+ ? false
1371
+ : childLocation !== undefined && !pathHasNodeModules(childLocation)
1372
+ ? true
1373
+ : state.watched;
1374
+ queue.push({ url: edge.child, watched: childWatched });
1375
+ }
1376
+ }
1377
+ return watched;
1378
+ }
1379
+
419
1380
  function hasOwn(value: Record<string, unknown>, key: string): boolean {
420
1381
  return Object.prototype.hasOwnProperty.call(value, key);
421
1382
  }
@@ -503,7 +1464,9 @@ function collectPluginObjects(value: unknown): Array<Record<string, unknown>> {
503
1464
  }
504
1465
 
505
1466
  function extractPluginSource(value: unknown): string | undefined {
506
- if (typeof value === "string") return value;
1467
+ if (typeof value === "string") {
1468
+ value = requireFromConfig(value);
1469
+ }
507
1470
  if (!isObject(value)) return undefined;
508
1471
  // ESM-from-CJS interop wraps CJS modules' \`exports.default\` so the
509
1472
  // plugin object can land under a \`.default\` indirection. Walk a few
@@ -525,30 +1488,46 @@ function extractPluginSource(value: unknown): string | undefined {
525
1488
  }
526
1489
  `;
527
1490
  /**
528
- * Resolves the contributor plugin entries declared in a .ts/.mjs lint config,
1491
+ * Resolves contributor plugin entries declared in any executable lint config,
529
1492
  * memoized through the shared on-disk config cache.
530
1493
  *
531
1494
  * Evaluating such a config spawns a full `ttsx` subprocess. A monorepo build
532
1495
  * runs one `ttsc` process per package, and each would otherwise re-spawn `ttsx`
533
1496
  * for the same shared config; the cache collapses that to a single evaluation.
534
- * The cache is keyed by the config file's path and exact contents (see
535
- * `configCacheKey`), so an edit re-evaluates cleanly.
1497
+ * The cache key covers the entry's path and exact contents; the payload also
1498
+ * fingerprints every local module reached from that entry. An entry or helper
1499
+ * edit therefore re-evaluates cleanly without treating installed packages as
1500
+ * project watch inputs.
536
1501
  */
537
1502
  function readTtsxConfigPlugins(configPath, context) {
538
- const cacheKey = configCacheKey("plugins", configPath);
1503
+ const resolutionRoot = node_path_1.default.resolve(pluginConfigBaseDir(context));
1504
+ const cacheKey = configCacheKey(`plugins\0${resolutionRoot}`, configPath);
539
1505
  if (cacheKey) {
540
1506
  const cached = readConfigPluginCache(cacheKey);
541
1507
  // Re-validate cached entries before trusting them: a contributor's
542
1508
  // resolved `source` directory may have moved since the entry was
543
1509
  // written. A stale entry falls through to a fresh evaluation rather
544
1510
  // than being forwarded to ttsc's plugin builder as a dead path.
545
- if (cached && cached.every(isValidConfigPluginEntry))
546
- return cached;
1511
+ if (cached &&
1512
+ cached.entries.every(isValidConfigPluginEntry) &&
1513
+ configDependenciesAreCurrent(cached.dependencies)) {
1514
+ return cached.entries;
1515
+ }
1516
+ }
1517
+ // A config can be saved while it is being evaluated. Retry a bounded number
1518
+ // of times until every dependency still has the bytes the module hook saw.
1519
+ // A continuously changing config remains usable but is deliberately not
1520
+ // cached; watch will schedule another cycle.
1521
+ let evaluation;
1522
+ for (let attempt = 0; attempt < 3; attempt++) {
1523
+ evaluation = evaluateTtsxConfigPlugins(configPath, context);
1524
+ if (configDependenciesAreCurrent(evaluation.dependencies)) {
1525
+ if (cacheKey)
1526
+ writeConfigPluginCache(cacheKey, evaluation);
1527
+ return evaluation.entries;
1528
+ }
547
1529
  }
548
- const entries = evaluateTtsxConfigPlugins(configPath, context);
549
- if (cacheKey)
550
- writeConfigPluginCache(cacheKey, entries);
551
- return entries;
1530
+ return evaluation.entries;
552
1531
  }
553
1532
  /**
554
1533
  * Reports whether a cached plugin entry is still usable: a well-formed
@@ -574,13 +1553,16 @@ function isValidConfigPluginEntry(entry) {
574
1553
  return false;
575
1554
  }
576
1555
  }
577
- function evaluateTtsxConfigPlugins(configPath, _context) {
1556
+ function evaluateTtsxConfigPlugins(configPath, context) {
578
1557
  const tempDir = realpathIfPossible(node_fs_1.default.mkdtempSync(node_path_1.default.join(loaderTempBase(configPath), "ttsc-lint-cfg-")));
579
1558
  try {
580
1559
  linkNearestNodeModules(tempDir, node_path_1.default.dirname(configPath));
581
1560
  const loaderPath = node_path_1.default.join(tempDir, "loader.mts");
1561
+ const outputPath = node_path_1.default.join(tempDir, "result.json");
582
1562
  const tsconfigPath = node_path_1.default.join(tempDir, "tsconfig.json");
583
- const loaderSource = TTSX_EXTRACTOR_SCRIPT.replace("%CONFIG_IMPORT%", JSON.stringify((0, node_url_1.pathToFileURL)(configPath).href));
1563
+ const loaderSource = exports.TTSX_EXTRACTOR_SCRIPT.replace("%CONFIG_IMPORT%", JSON.stringify((0, node_url_1.pathToFileURL)(configPath).href))
1564
+ .replace("%CONFIG_OUTPUT%", JSON.stringify(outputPath))
1565
+ .replace("%CONFIG_ROOT%", JSON.stringify(node_path_1.default.resolve(pluginConfigBaseDir(context))));
584
1566
  node_fs_1.default.writeFileSync(loaderPath, loaderSource, "utf8");
585
1567
  node_fs_1.default.writeFileSync(tsconfigPath, JSON.stringify({
586
1568
  compilerOptions: {
@@ -604,10 +1586,16 @@ function evaluateTtsxConfigPlugins(configPath, _context) {
604
1586
  },
605
1587
  files: [
606
1588
  loaderPath.replace(/\\/g, "/"),
607
- configPath.replace(/\\/g, "/"),
1589
+ ...(node_path_1.default.extname(configPath).toLowerCase() === ".json"
1590
+ ? []
1591
+ : [configPath.replace(/\\/g, "/")]),
608
1592
  ],
609
1593
  }, null, 2), "utf8");
610
- const ttsxBinary = process.env.TTSC_TTSX_BINARY ?? "ttsx";
1594
+ // The config comes first, so a project that pins its own ttsc gets it. This
1595
+ // descriptor's own location comes second, because a fixture or a workspace
1596
+ // that installs only the lint package cannot resolve ttsc from the config
1597
+ // at all, and the descriptor always sits beside the host that loaded it.
1598
+ const ttsxBinary = resolveTtsxLauncher([configPath, context.dirname]);
611
1599
  // `--no-plugins` keeps this build hermetic: the loader only needs to
612
1600
  // type-check and run the user's lint config to extract its plugin
613
1601
  // entries. Loading the host project's transform/check plugins
@@ -632,11 +1620,13 @@ function evaluateTtsxConfigPlugins(configPath, _context) {
632
1620
  env,
633
1621
  encoding: "utf8",
634
1622
  maxBuffer: 1024 * 1024 * 16,
1623
+ stdio: ["ignore", "pipe", "pipe"],
635
1624
  // 60s cap so a runaway top-level await / infinite loop in the
636
1625
  // user's lint config can't hang the entire ttsc invocation.
637
1626
  timeout: 60_000,
638
1627
  windowsHide: true,
639
1628
  });
1629
+ forwardConfigEvaluatorStreams(result.stdout, result.stderr);
640
1630
  if (result.error) {
641
1631
  throw new Error(`@ttsc/lint: failed to spawn ttsx for ${configPath}: ${result.error.message}`);
642
1632
  }
@@ -645,21 +1635,33 @@ function evaluateTtsxConfigPlugins(configPath, _context) {
645
1635
  `(likely the 60s timeout). Simplify the config or move heavy work out of top-level.`);
646
1636
  }
647
1637
  if (result.status !== 0) {
648
- throw new Error(`@ttsc/lint: lint config ${configPath} evaluation failed:\n${result.stderr || result.stdout}`);
1638
+ // The evaluator already said why on its own stderr. Reporting only the
1639
+ // exit code discards that and leaves the caller — a test, a CI log, a
1640
+ // user with a typo in one contributor — holding a number.
1641
+ const reason = configEvaluatorFailureReason(result.stderr);
1642
+ throw new Error(`@ttsc/lint: lint config ${configPath} evaluation failed with exit code ${String(result.status)}` +
1643
+ (reason === "" ? "" : "\n" + reason));
649
1644
  }
650
1645
  let payload;
651
1646
  try {
652
- payload = JSON.parse(result.stdout);
1647
+ payload = JSON.parse(node_fs_1.default.readFileSync(outputPath, "utf8"));
653
1648
  }
654
1649
  catch (error) {
655
1650
  throw new Error(`@ttsc/lint: lint config ${configPath} evaluator returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
656
1651
  }
657
- const entries = payload.entries ?? [];
658
- return entries.map((entry) => {
1652
+ if (!Array.isArray(payload.entries)) {
1653
+ throw new Error(`@ttsc/lint: lint config ${configPath} evaluator omitted its plugin-entry array`);
1654
+ }
1655
+ const entries = payload.entries.map((entry) => {
659
1656
  // The ttsx extractor already resolved each plugin object's
660
1657
  // `source` to an absolute directory path. Validate the shape but
661
1658
  // skip the specifier-resolution branch — re-routing a directory
662
1659
  // through `createRequire().resolve` would fail.
1660
+ if (entry === null ||
1661
+ typeof entry !== "object" ||
1662
+ typeof entry.namespace !== "string") {
1663
+ throw new Error(`@ttsc/lint: lint config ${configPath} evaluator returned a malformed plugin entry`);
1664
+ }
663
1665
  if (!NAMESPACE_PATTERN.test(entry.namespace)) {
664
1666
  throw new Error(`@ttsc/lint: lint config ${configPath} namespace ${JSON.stringify(entry.namespace)} must match /^[a-z][a-z0-9_-]*$/`);
665
1667
  }
@@ -675,11 +1677,40 @@ function evaluateTtsxConfigPlugins(configPath, _context) {
675
1677
  }
676
1678
  return { namespace: entry.namespace, source: entry.source };
677
1679
  });
1680
+ const dependencies = normalizeConfigDependencyFingerprints(payload.dependencies);
1681
+ if (dependencies === undefined) {
1682
+ throw new Error(`@ttsc/lint: lint config ${configPath} evaluator returned malformed dependency fingerprints`);
1683
+ }
1684
+ return { dependencies, entries };
678
1685
  }
679
1686
  finally {
680
1687
  node_fs_1.default.rmSync(tempDir, { recursive: true, force: true });
681
1688
  }
682
1689
  }
1690
+ /**
1691
+ * What the evaluator said before it gave up, trimmed to the part that explains
1692
+ * it.
1693
+ *
1694
+ * The build banner and progress lines are the same on success, so they say
1695
+ * nothing about the failure; the tail is where the thrown reason lands. Kept to
1696
+ * a few lines because this is appended to an exception message, not a log.
1697
+ */
1698
+ function configEvaluatorFailureReason(stderr) {
1699
+ const lines = (stderr ?? "")
1700
+ .split(/\r?\n/)
1701
+ .map((line) => line.trimEnd())
1702
+ .filter((line) => line.trim() !== "");
1703
+ return lines.slice(-CONFIG_EVALUATOR_REASON_LINES).join("\n");
1704
+ }
1705
+ const CONFIG_EVALUATOR_REASON_LINES = 5;
1706
+ function forwardConfigEvaluatorStreams(stdout, stderr) {
1707
+ // Both child streams are human output. Parent stdout is reserved for compiler
1708
+ // JSON or LSP frames, so even a user console.log is redirected.
1709
+ if (stdout)
1710
+ process.stderr.write(stdout);
1711
+ if (stderr)
1712
+ process.stderr.write(stderr);
1713
+ }
683
1714
  // ────────────────────────────────────────────────────────────────────────────
684
1715
  // Config cache (shared with the Go sidecar — packages/lint/linthost/config.go)
685
1716
  // ────────────────────────────────────────────────────────────────────────────
@@ -687,7 +1718,7 @@ function evaluateTtsxConfigPlugins(configPath, _context) {
687
1718
  * Namespaces the on-disk config cache. Kept in lockstep with the Go sidecar's
688
1719
  * `configCacheVersion`; bump both when the cached shape changes.
689
1720
  */
690
- const CONFIG_CACHE_VERSION = "v2";
1721
+ const CONFIG_CACHE_VERSION = "v5";
691
1722
  /**
692
1723
  * Directory shared by this factory and the Go sidecar for cached lint configs.
693
1724
  * The two write different files (the `kind` segment of the cache key keeps
@@ -741,7 +1772,19 @@ function readConfigPluginCache(cacheKey) {
741
1772
  }
742
1773
  try {
743
1774
  const parsed = JSON.parse(body);
744
- return Array.isArray(parsed) ? parsed : undefined;
1775
+ if (parsed === null ||
1776
+ typeof parsed !== "object" ||
1777
+ !Array.isArray(parsed.entries) ||
1778
+ !Array.isArray(parsed.dependencies)) {
1779
+ return undefined;
1780
+ }
1781
+ const dependencies = normalizeConfigDependencyFingerprints(parsed.dependencies);
1782
+ if (dependencies === undefined)
1783
+ return undefined;
1784
+ return {
1785
+ dependencies,
1786
+ entries: parsed.entries,
1787
+ };
745
1788
  }
746
1789
  catch {
747
1790
  return undefined;
@@ -753,18 +1796,150 @@ function readConfigPluginCache(cacheKey) {
753
1796
  * temp-file + rename keeps a concurrent reader in a sibling `ttsc` process from
754
1797
  * observing a half-written file.
755
1798
  */
756
- function writeConfigPluginCache(cacheKey, entries) {
1799
+ function writeConfigPluginCache(cacheKey, evaluation) {
757
1800
  try {
758
1801
  const dir = configCacheDir();
759
1802
  node_fs_1.default.mkdirSync(dir, { recursive: true });
760
- const tmp = node_path_1.default.join(dir, `${cacheKey}.${process.pid}.tmp`);
761
- node_fs_1.default.writeFileSync(tmp, JSON.stringify(entries), "utf8");
762
- node_fs_1.default.renameSync(tmp, node_path_1.default.join(dir, `${cacheKey}.json`));
1803
+ const tmp = node_path_1.default.join(dir, `${cacheKey}.${process.pid}.${(0, node_crypto_1.randomUUID)()}.tmp`);
1804
+ try {
1805
+ node_fs_1.default.writeFileSync(tmp, JSON.stringify(evaluation), "utf8");
1806
+ node_fs_1.default.renameSync(tmp, node_path_1.default.join(dir, `${cacheKey}.json`));
1807
+ }
1808
+ finally {
1809
+ try {
1810
+ node_fs_1.default.unlinkSync(tmp);
1811
+ }
1812
+ catch {
1813
+ // A successful rename already consumed the temporary path.
1814
+ }
1815
+ }
763
1816
  }
764
1817
  catch {
765
1818
  // Cold cache on failure — the next invocation re-evaluates.
766
1819
  }
767
1820
  }
1821
+ function normalizeConfigDependencyFingerprints(value) {
1822
+ if (!Array.isArray(value) || value.length === 0)
1823
+ return undefined;
1824
+ const dependencies = new Map();
1825
+ for (const candidate of value) {
1826
+ if (candidate === null ||
1827
+ typeof candidate !== "object" ||
1828
+ typeof candidate.path !== "string" ||
1829
+ typeof candidate.digest !== "string" ||
1830
+ !["directory", "file", "optional-file"].includes(candidate.kind) ||
1831
+ !["cache", "watch"].includes(candidate.scope)) {
1832
+ return undefined;
1833
+ }
1834
+ const candidatePath = candidate.path;
1835
+ const digest = candidate.digest;
1836
+ const kind = candidate.kind;
1837
+ const scope = candidate.scope;
1838
+ if (!node_path_1.default.isAbsolute(candidatePath) || !/^[0-9a-f]{64}$/.test(digest)) {
1839
+ return undefined;
1840
+ }
1841
+ const location = node_path_1.default.resolve(candidatePath);
1842
+ const previous = dependencies.get(location);
1843
+ if (previous !== undefined &&
1844
+ (previous.digest !== digest ||
1845
+ previous.kind !== kind ||
1846
+ previous.scope !== scope)) {
1847
+ return undefined;
1848
+ }
1849
+ dependencies.set(location, {
1850
+ digest,
1851
+ kind,
1852
+ path: location,
1853
+ scope,
1854
+ });
1855
+ }
1856
+ return [...dependencies.values()].sort((left, right) => left.path.localeCompare(right.path));
1857
+ }
1858
+ function configDependenciesAreCurrent(dependencies) {
1859
+ if (dependencies.length === 0)
1860
+ return false;
1861
+ return dependencies.every((dependency) => {
1862
+ if (!/^[0-9a-f]{64}$/.test(dependency.digest))
1863
+ return false;
1864
+ try {
1865
+ const digest = dependency.kind === "directory"
1866
+ ? configDirectoryDigest(dependency.path)
1867
+ : dependency.kind === "optional-file"
1868
+ ? configOptionalFileDigest(dependency.path)
1869
+ : (0, node_crypto_1.createHash)("sha256")
1870
+ .update(node_fs_1.default.readFileSync(dependency.path))
1871
+ .digest("hex");
1872
+ return digest === dependency.digest;
1873
+ }
1874
+ catch {
1875
+ return false;
1876
+ }
1877
+ });
1878
+ }
1879
+ function configDirectoryDigest(location) {
1880
+ const entries = [];
1881
+ if (process.platform === "win32") {
1882
+ for (const entry of node_fs_1.default.readdirSync(location, { withFileTypes: true })) {
1883
+ let target = node_buffer_1.Buffer.alloc(0);
1884
+ if (entry.isSymbolicLink()) {
1885
+ try {
1886
+ target = node_buffer_1.Buffer.from(node_fs_1.default.readlinkSync(node_path_1.default.join(location, entry.name)), "utf8");
1887
+ }
1888
+ catch {
1889
+ target = node_buffer_1.Buffer.from("<unreadable>");
1890
+ }
1891
+ }
1892
+ entries.push(configDirectoryDigestRecord(node_buffer_1.Buffer.from(entry.name), entry, target));
1893
+ }
1894
+ }
1895
+ else {
1896
+ for (const entry of node_fs_1.default.readdirSync(location, {
1897
+ encoding: "buffer",
1898
+ withFileTypes: true,
1899
+ })) {
1900
+ let target = node_buffer_1.Buffer.alloc(0);
1901
+ if (entry.isSymbolicLink()) {
1902
+ try {
1903
+ target = node_fs_1.default.readlinkSync(node_buffer_1.Buffer.concat([
1904
+ node_buffer_1.Buffer.from(location),
1905
+ node_buffer_1.Buffer.from(node_path_1.default.sep),
1906
+ entry.name,
1907
+ ]), { encoding: "buffer" });
1908
+ }
1909
+ catch {
1910
+ target = node_buffer_1.Buffer.from("<unreadable>");
1911
+ }
1912
+ }
1913
+ entries.push(configDirectoryDigestRecord(entry.name, entry, target));
1914
+ }
1915
+ }
1916
+ entries.sort(node_buffer_1.Buffer.compare);
1917
+ const serialized = node_buffer_1.Buffer.concat(entries.flatMap((entry, index) => index === 0 ? [entry] : [node_buffer_1.Buffer.from([0]), entry]));
1918
+ return (0, node_crypto_1.createHash)("sha256").update(serialized).digest("hex");
1919
+ }
1920
+ function configDirectoryDigestRecord(name, entry, target) {
1921
+ const kind = entry.isDirectory()
1922
+ ? "directory"
1923
+ : entry.isFile()
1924
+ ? "file"
1925
+ : entry.isSymbolicLink()
1926
+ ? "symlink"
1927
+ : "other";
1928
+ return node_buffer_1.Buffer.concat([name, node_buffer_1.Buffer.from("\0" + kind + "\0"), target]);
1929
+ }
1930
+ function configOptionalFileDigest(location) {
1931
+ try {
1932
+ if (node_fs_1.default.statSync(location).isFile()) {
1933
+ return (0, node_crypto_1.createHash)("sha256")
1934
+ .update(node_buffer_1.Buffer.concat([node_buffer_1.Buffer.from("file\0"), node_fs_1.default.readFileSync(location)]))
1935
+ .digest("hex");
1936
+ }
1937
+ }
1938
+ catch {
1939
+ // Missing, unreadable, and non-file candidates share the absent state.
1940
+ }
1941
+ return (0, node_crypto_1.createHash)("sha256").update("missing\0").digest("hex");
1942
+ }
768
1943
  // ────────────────────────────────────────────────────────────────────────────
769
1944
  // Shared helpers
770
1945
  // ────────────────────────────────────────────────────────────────────────────
@@ -945,6 +2120,43 @@ function nodeConfigLoaderEnv(configPath) {
945
2120
  }
946
2121
  return env;
947
2122
  }
2123
+ /**
2124
+ * Where the isolated config evaluator lives.
2125
+ *
2126
+ * An explicit override wins. Otherwise the launcher is resolved out of a ttsc
2127
+ * installation one of the anchors can see, because a bare command name only
2128
+ * works when a bin link happens to be on PATH — which it is for a spawned CLI
2129
+ * and is not for a host that loaded this descriptor in process. The bare name
2130
+ * remains the last resort for an installation none of them reach.
2131
+ */
2132
+ function resolveTtsxLauncher(anchors) {
2133
+ const explicit = process.env.TTSC_TTSX_BINARY?.trim();
2134
+ if (explicit)
2135
+ return explicit;
2136
+ for (const anchor of anchors) {
2137
+ const launcher = ttsxLauncherFrom(anchor);
2138
+ if (launcher !== undefined)
2139
+ return launcher;
2140
+ }
2141
+ return "ttsx";
2142
+ }
2143
+ function ttsxLauncherFrom(anchor) {
2144
+ try {
2145
+ // Only the manifest is exported, so the launcher is derived from where the
2146
+ // manifest resolved rather than requested as a subpath. Resolution is
2147
+ // anchored on the config being evaluated, which is how every other
2148
+ // resolution in this descriptor is anchored and picks the ttsc the project
2149
+ // actually installed.
2150
+ const manifest = (0, node_module_1.createRequire)(anchor).resolve("ttsc/package.json");
2151
+ const launcher = node_path_1.default.join(node_path_1.default.dirname(manifest), "lib", "launcher", "ttsx.js");
2152
+ if (node_fs_1.default.existsSync(launcher))
2153
+ return launcher;
2154
+ }
2155
+ catch {
2156
+ // This anchor cannot see ttsc; the caller tries the next one.
2157
+ }
2158
+ return undefined;
2159
+ }
948
2160
  function ttsxThroughNodeIfNeeded(binary) {
949
2161
  const ext = node_path_1.default.extname(binary).toLowerCase();
950
2162
  if ([".js", ".cjs", ".mjs", ".ts", ".cts", ".mts"].includes(ext)) {