@ariestools/toolchain 8.7.5 → 8.7.7

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/bin/xy.mjs CHANGED
@@ -23099,7 +23099,7 @@ function isTerminalPackage$1(location) {
23099
23099
  //#region src/actions/deplint/checkPackage/getUnsatisfiedPeerDependencies.ts
23100
23100
  /** True when the policy (if any) obliges this package to forward `peer`. */
23101
23101
  function isPeerForwarded(policy, peer) {
23102
- return policy === void 0 || policy.mode === "always" || policy.importedModules.has(peer);
23102
+ return policy === void 0 || policy.mode === "always" || policy.importedModules.has(peer) || (policy.vouchedPeers?.has(peer) ?? false);
23103
23103
  }
23104
23104
  function readDepPackageJson(location, dep) {
23105
23105
  const depPkgPath = findDepPackageJson(location, dep);
@@ -23546,16 +23546,34 @@ const AEI_RULES = [
23546
23546
  },
23547
23547
  {
23548
23548
  defaultWeight: 0,
23549
- description: "Peer contract inherited from a runtime dependency chain for a package never imported here (peerForwarding: when-used) — installers resolve it; no forwarding required",
23549
+ description: "Peer contract inherited from a runtime dependency chain for a package neither imported nor exposed here (peerForwarding: when-used) — installers resolve it; no forwarding required",
23550
23550
  id: "aei.signal.inherited-peer",
23551
23551
  kind: "dep-signal"
23552
23552
  },
23553
+ {
23554
+ defaultWeight: 0,
23555
+ description: "Chain peer neither exposed through the package API nor value-imported (peerForwarding: when-exposed) — declaring it in own dependencies (provider pattern) discharges the contract",
23556
+ id: "aei.signal.absorbable-peer",
23557
+ kind: "dep-signal"
23558
+ },
23559
+ {
23560
+ defaultWeight: 0,
23561
+ description: "Peer contract imposed only by dependency chains whose roots this package imports exclusively as types — the chains never execute here, so no runtime contract exists to forward",
23562
+ id: "aei.signal.type-only-chain-peer",
23563
+ kind: "dep-signal"
23564
+ },
23553
23565
  {
23554
23566
  defaultWeight: 40,
23555
23567
  description: "Dependency uses a global registry",
23556
23568
  id: "aei.signal.global-registry",
23557
23569
  kind: "dep-signal"
23558
23570
  },
23571
+ {
23572
+ defaultWeight: 40,
23573
+ description: "Dependency creates React contexts at module scope (a duplicate copy forks the context)",
23574
+ id: "aei.signal.creates-context",
23575
+ kind: "dep-signal"
23576
+ },
23559
23577
  {
23560
23578
  defaultWeight: 30,
23561
23579
  description: "Dependency exports mutable objects",
@@ -23705,7 +23723,7 @@ function matchingOverrides(packages, dependency) {
23705
23723
  return exact === void 0 ? globs : [...globs, exact];
23706
23724
  }
23707
23725
  function resolvePeerForwarding(peerForwarding = "always") {
23708
- if (peerForwarding !== "always" && peerForwarding !== "when-used") throw new TypeError("commands.apiExposure.peerForwarding must be \"always\" or \"when-used\"");
23726
+ if (peerForwarding !== "always" && peerForwarding !== "when-used" && peerForwarding !== "when-exposed") throw new TypeError("commands.apiExposure.peerForwarding must be \"always\", \"when-used\", or \"when-exposed\"");
23709
23727
  return peerForwarding;
23710
23728
  }
23711
23729
  function normalizeApiExposureConfig(config) {
@@ -24076,14 +24094,71 @@ function findPnpmVirtualStoreEntries(startDir) {
24076
24094
  current = parent;
24077
24095
  }
24078
24096
  }
24097
+ /** Walks up from `startDir` looking for a `pnpm-lock.yaml`. */
24098
+ function findPnpmLockfile(startDir) {
24099
+ let current = PATH.resolve(startDir);
24100
+ while (true) {
24101
+ const candidate = PATH.join(current, "pnpm-lock.yaml");
24102
+ if (fs.existsSync(candidate)) return candidate;
24103
+ const parent = PATH.dirname(current);
24104
+ if (parent === current) return void 0;
24105
+ current = parent;
24106
+ }
24107
+ }
24108
+ const lockfileVersionsCache = /* @__PURE__ */ new Map();
24109
+ /**
24110
+ * Package-key lines of the lockfile's `packages:` section, e.g.
24111
+ * ` '@mui/material@9.2.0':` (v9), ` react@19.2.7:` (v9 unquoted) or
24112
+ * ` /@mui/material@9.2.0(react@19.2.7):` (v6).
24113
+ */
24114
+ const LOCKFILE_PACKAGE_KEY = /^ {2}['"]?\/?((?:@[^/'"\s]+\/)?[^@/'"\s]+)@([^('":\s]+)/;
24115
+ /**
24116
+ * Resolved versions per package name from the lockfile's `packages:` section.
24117
+ * The lockfile is authoritative for what an install produces — unlike the
24118
+ * `.pnpm` virtual store directory, which can hold stale entries from prior
24119
+ * installs.
24120
+ */
24121
+ function readLockfileVersions(lockfilePath) {
24122
+ if (lockfileVersionsCache.has(lockfilePath)) return lockfileVersionsCache.get(lockfilePath);
24123
+ let versions;
24124
+ try {
24125
+ const lines = fs.readFileSync(lockfilePath, "utf8").split("\n");
24126
+ versions = /* @__PURE__ */ new Map();
24127
+ let inPackagesSection = false;
24128
+ for (const line of lines) {
24129
+ if (line.length > 0 && line[0] !== " " && line[0] !== "#") {
24130
+ inPackagesSection = line.startsWith("packages:");
24131
+ continue;
24132
+ }
24133
+ if (!inPackagesSection) continue;
24134
+ const match = LOCKFILE_PACKAGE_KEY.exec(line);
24135
+ if (match === null) continue;
24136
+ const [, name, version] = match;
24137
+ const set = versions.get(name) ?? /* @__PURE__ */ new Set();
24138
+ set.add(version);
24139
+ versions.set(name, set);
24140
+ }
24141
+ } catch {
24142
+ versions = void 0;
24143
+ }
24144
+ lockfileVersionsCache.set(lockfilePath, versions);
24145
+ return versions;
24146
+ }
24079
24147
  /**
24080
24148
  * True when the install tree holds more than one version of the dependency —
24081
24149
  * the duplication-risk condition of the tree-shaking modifier
24082
- * (API-EXPOSURE-INDEX.md section 9). Only the pnpm virtual store can be read
24083
- * cheaply; on other layouts the answer is unknown, so the modifier keeps its
24084
- * historical behavior and applies.
24150
+ * (API-EXPOSURE-INDEX.md section 9). The pnpm lockfile is the authoritative
24151
+ * source; the `.pnpm` virtual store directory is the fallback (it can hold
24152
+ * stale entries from prior installs, so it may over-report). On other
24153
+ * layouts the answer is unknown, so the modifier keeps its historical
24154
+ * behavior and applies.
24085
24155
  */
24086
24156
  function hasInstalledVersionMultiplicity(workspaceDir, dependency) {
24157
+ const lockfilePath = findPnpmLockfile(workspaceDir);
24158
+ if (lockfilePath !== void 0) {
24159
+ const lockfileVersions = readLockfileVersions(lockfilePath);
24160
+ if (lockfileVersions !== void 0) return (lockfileVersions.get(dependency)?.size ?? 0) > 1;
24161
+ }
24087
24162
  const entries = findPnpmVirtualStoreEntries(workspaceDir);
24088
24163
  if (entries === void 0) return true;
24089
24164
  const prefix = `${dependency.replace("/", "+")}@`;
@@ -24134,6 +24209,69 @@ function hasEsmSurface(manifest) {
24134
24209
  if (typeof exportsField === "object" && exportsField !== null) return firstStringDeep(exportsField, ["import"]) !== void 0 || JSON.stringify(exportsField).includes("\"import\"");
24135
24210
  return false;
24136
24211
  }
24212
+ const CONTEXT_CREATION_PATTERN = /\bcreateContext\s*\(/;
24213
+ /** Bounds for the shipped-runtime context scan (large deps like MUI). */
24214
+ const MAX_CONTEXT_SCAN_FILES = 400;
24215
+ const MAX_CONTEXT_SCAN_BYTES = 8e6;
24216
+ const RUNTIME_FILE_PATTERN = /\.(?:js|mjs|cjs)$/;
24217
+ const createsContextCache = /* @__PURE__ */ new Map();
24218
+ /** Collects shipped runtime files, capped, skipping nested node_modules. */
24219
+ function collectRuntimeFiles(dir, collected) {
24220
+ if (collected.length >= MAX_CONTEXT_SCAN_FILES * 4) return;
24221
+ let entries;
24222
+ try {
24223
+ entries = fs.readdirSync(dir, { withFileTypes: true });
24224
+ } catch {
24225
+ return;
24226
+ }
24227
+ for (const entry of entries) {
24228
+ if (collected.length >= MAX_CONTEXT_SCAN_FILES * 4) return;
24229
+ const entryPath = PATH.join(dir, entry.name);
24230
+ if (entry.isDirectory()) {
24231
+ if (entry.name !== "node_modules") collectRuntimeFiles(entryPath, collected);
24232
+ } else if (entry.isFile() && RUNTIME_FILE_PATTERN.test(entry.name)) collected.push(entryPath);
24233
+ }
24234
+ }
24235
+ /**
24236
+ * Bounded scan of the dependency's shipped runtime for module-scope context
24237
+ * creation (`createContext(`). Context-named files are scanned first — the
24238
+ * conventional home of the pattern — so large dependencies resolve within
24239
+ * the scan budget.
24240
+ */
24241
+ function createsSharedContext(dependencyDir) {
24242
+ const cached = createsContextCache.get(dependencyDir);
24243
+ if (cached !== void 0) return cached;
24244
+ const files = [];
24245
+ collectRuntimeFiles(dependencyDir, files);
24246
+ const prioritized = files.toSorted((a, b) => Number(/context/i.test(b)) - Number(/context/i.test(a)));
24247
+ let scannedFiles = 0;
24248
+ let scannedBytes = 0;
24249
+ let result = false;
24250
+ for (const file of prioritized) {
24251
+ if (scannedFiles >= MAX_CONTEXT_SCAN_FILES || scannedBytes >= MAX_CONTEXT_SCAN_BYTES) break;
24252
+ try {
24253
+ const content = fs.readFileSync(file, "utf8");
24254
+ scannedFiles += 1;
24255
+ scannedBytes += content.length;
24256
+ if (CONTEXT_CREATION_PATTERN.test(content)) {
24257
+ result = true;
24258
+ break;
24259
+ }
24260
+ } catch {
24261
+ continue;
24262
+ }
24263
+ }
24264
+ createsContextCache.set(dependencyDir, result);
24265
+ return result;
24266
+ }
24267
+ /**
24268
+ * True for packages in the React-singleton class: React itself and libraries
24269
+ * designed to share the host's React copy. Scopes the context scan so
24270
+ * unrelated uses of `createContext` (e.g. `node:vm`) don't fire the signal.
24271
+ */
24272
+ function isReactAdjacent(dependency, manifest) {
24273
+ return dependency === "react" || dependency === "react-dom" || Object.hasOwn(manifest.peerDependencies ?? {}, "react");
24274
+ }
24137
24275
  /** Syntactic scan of the dependency's types entry point. */
24138
24276
  function scanTypesSurface(typesEntry) {
24139
24277
  let sourceCode;
@@ -24187,6 +24325,7 @@ function getDependencySignals(workspaceDir, dependency) {
24187
24325
  if (manifest.peerDependencies !== void 0 && Object.keys(manifest.peerDependencies).length > 0) report("aei.signal.declares-peers", `${dependency} declares peerDependencies of its own`);
24188
24326
  const sideEffectsFree = manifest.sideEffects === false;
24189
24327
  if (sideEffectsFree) report("aei.signal.side-effects-free", `${dependency} declares sideEffects: false`);
24328
+ if (isReactAdjacent(dependency, manifest) && createsSharedContext(dependencyDir)) report("aei.signal.creates-context", `${dependency} creates React contexts at module scope — a duplicate copy forks the context`);
24190
24329
  const typesEntry = resolveTypesEntry(dependencyDir, manifest);
24191
24330
  const surface = typesEntry === void 0 ? void 0 : scanTypesSurface(typesEntry);
24192
24331
  if (surface !== void 0) {
@@ -24510,6 +24649,88 @@ function getExposureFindings({ entryFiles, fileLabel, program }) {
24510
24649
  return findings;
24511
24650
  }
24512
24651
  //#endregion
24652
+ //#region src/actions/deplint/sourceFileCache.ts
24653
+ const cache$2 = /* @__PURE__ */ new Map();
24654
+ function scriptKindForPath(filePath) {
24655
+ if (/\.(?:mjs|cjs|js)$/i.test(filePath)) return ts.ScriptKind.JS;
24656
+ if (/\.tsx$/i.test(filePath)) return ts.ScriptKind.TSX;
24657
+ if (/\.jsx$/i.test(filePath)) return ts.ScriptKind.JSX;
24658
+ }
24659
+ function getCachedSourceFile(filePath) {
24660
+ const cached = cache$2.get(filePath);
24661
+ if (cached !== void 0) return cached;
24662
+ const sourceCode = fs.readFileSync(filePath, "utf8");
24663
+ const entry = {
24664
+ sourceCode,
24665
+ sourceFile: ts.createSourceFile(PATH.basename(filePath), sourceCode, ts.ScriptTarget.Latest, true, scriptKindForPath(filePath))
24666
+ };
24667
+ cache$2.set(filePath, entry);
24668
+ return entry;
24669
+ }
24670
+ /** Like getCachedSourceFile, but returns undefined when the file cannot be read. */
24671
+ function tryGetCachedSourceFile(filePath) {
24672
+ const cached = cache$2.get(filePath);
24673
+ if (cached !== void 0) return cached;
24674
+ try {
24675
+ return getCachedSourceFile(filePath);
24676
+ } catch {
24677
+ return;
24678
+ }
24679
+ }
24680
+ function clearSourceFileCache() {
24681
+ cache$2.clear();
24682
+ }
24683
+ //#endregion
24684
+ //#region src/actions/deplint/getImportsFromFile.ts
24685
+ function isTypeOnlyImportClause(clause) {
24686
+ if (clause === void 0) return false;
24687
+ if ("phaseModifier" in clause) {
24688
+ const mod = clause.phaseModifier;
24689
+ return (typeof mod === "number" ? mod : mod?.kind) === ts.SyntaxKind.TypeKeyword;
24690
+ }
24691
+ return clause.isTypeOnly ?? false;
24692
+ }
24693
+ function getImportsFromFile(filePath, importPaths, typeImportPaths) {
24694
+ const { sourceFile } = getCachedSourceFile(filePath);
24695
+ const imports = [];
24696
+ const typeImports = [];
24697
+ const isDeclarationFile = filePath.endsWith(".d.ts") || filePath.endsWith(".d.mts") || filePath.endsWith(".d.cts");
24698
+ function visit(node) {
24699
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
24700
+ const moduleSpecifier = node.moduleSpecifier?.getFullText();
24701
+ const isTypeImport = ts.isImportDeclaration(node) ? isTypeOnlyImportClause(node.importClause) : false;
24702
+ if (typeof moduleSpecifier === "string") {
24703
+ const trimmed = moduleSpecifier.replaceAll(/['"]/g, "").trim();
24704
+ if (isTypeImport || isDeclarationFile) typeImports.push(trimmed);
24705
+ else imports.push(trimmed);
24706
+ }
24707
+ } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
24708
+ const [arg] = node.arguments;
24709
+ if (ts.isStringLiteral(arg)) imports.push(arg.text);
24710
+ } else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "require" && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) imports.push(node.arguments[0].text);
24711
+ ts.forEachChild(node, visit);
24712
+ }
24713
+ visit(sourceFile);
24714
+ for (const ref of sourceFile.typeReferenceDirectives) typeImports.push(ref.fileName);
24715
+ const importsStartsWithExcludes = [
24716
+ ".",
24717
+ "#",
24718
+ "node:"
24719
+ ];
24720
+ const isValidImport = (imp) => importsStartsWithExcludes.every((exc) => !imp.startsWith(exc)) && !imp.includes("*") && !imp.includes("!");
24721
+ const cleanedImports = imports.filter(isValidImport).map(getBasePackageName);
24722
+ const cleanedTypeImports = typeImports.filter(isValidImport).map(getBasePackageName);
24723
+ for (const imp of cleanedImports) {
24724
+ importPaths[imp] ??= [];
24725
+ importPaths[imp].push(filePath);
24726
+ }
24727
+ for (const imp of cleanedTypeImports) {
24728
+ typeImportPaths[imp] ??= [];
24729
+ typeImportPaths[imp].push(filePath);
24730
+ }
24731
+ return [cleanedImports, cleanedTypeImports];
24732
+ }
24733
+ //#endregion
24513
24734
  //#region src/actions/api-exposure/analyzer/importedPackages.ts
24514
24735
  /**
24515
24736
  * Extracts the external package name from a module specifier, if any.
@@ -24521,29 +24742,56 @@ function packageNameFromSpecifier(specifier) {
24521
24742
  if (specifier.startsWith("@")) return parts.length > 1 ? `${parts[0]}/${parts[1]}` : void 0;
24522
24743
  return parts[0] === "" ? void 0 : parts[0];
24523
24744
  }
24524
- function collectFileImports(sourceFile, imported) {
24745
+ /**
24746
+ * True when every binding the statement introduces is type-only, so the
24747
+ * statement is erased at compile time and never executes the module.
24748
+ */
24749
+ function isTypeOnlyStatement(statement) {
24750
+ if (ts.isImportDeclaration(statement)) {
24751
+ const clause = statement.importClause;
24752
+ if (clause === void 0) return false;
24753
+ if (isTypeOnlyImportClause(clause)) return true;
24754
+ if (clause.name !== void 0) return false;
24755
+ const bindings = clause.namedBindings;
24756
+ return bindings !== void 0 && ts.isNamedImports(bindings) && bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly);
24757
+ }
24758
+ if (statement.isTypeOnly) return true;
24759
+ const clause = statement.exportClause;
24760
+ return clause !== void 0 && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly);
24761
+ }
24762
+ function collectFileImports(sourceFile, seen) {
24525
24763
  for (const statement of sourceFile.statements) {
24526
- const moduleSpecifier = ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement) ? statement.moduleSpecifier : void 0;
24764
+ if (!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) continue;
24765
+ const { moduleSpecifier } = statement;
24527
24766
  if (moduleSpecifier === void 0 || !ts.isStringLiteral(moduleSpecifier)) continue;
24528
24767
  const name = packageNameFromSpecifier(moduleSpecifier.text);
24529
- if (name !== void 0) imported.add(name);
24768
+ if (name === void 0) continue;
24769
+ if (isTypeOnlyStatement(statement)) seen.typeSeen.add(name);
24770
+ else seen.valueSeen.add(name);
24530
24771
  }
24531
24772
  }
24532
24773
  /**
24533
24774
  * Collects the external packages the workspace's own source files import
24534
- * (static imports and re-exports reachable from the entry points). This is
24535
- * the "does this package use the dependency itself" signal consumed by the
24536
- * `peerForwarding: 'when-used'` policy — a peer contract inherited from a
24537
- * dependency chain only forwards conclusively when the package appears here.
24775
+ * (static imports and re-exports reachable from the entry points), split
24776
+ * into value-position imports and exclusively-type-only imports. This feeds
24777
+ * two policies: `peerForwarding: 'when-used'`/`'when-exposed'` (does this
24778
+ * package need the peer itself) and the type-only chain-root check (does the
24779
+ * dependency imposing a peer contract ever execute here).
24538
24780
  */
24539
24781
  function getImportedPackages(program, workspaceDir) {
24540
- const imported = /* @__PURE__ */ new Set();
24782
+ const seen = {
24783
+ typeSeen: /* @__PURE__ */ new Set(),
24784
+ valueSeen: /* @__PURE__ */ new Set()
24785
+ };
24541
24786
  for (const sourceFile of program.getSourceFiles()) {
24542
24787
  const { fileName } = sourceFile;
24543
24788
  if (!fileName.startsWith(workspaceDir) || fileName.includes("node_modules")) continue;
24544
- collectFileImports(sourceFile, imported);
24789
+ collectFileImports(sourceFile, seen);
24545
24790
  }
24546
- return imported;
24791
+ return {
24792
+ typeOnly: new Set([...seen.typeSeen].filter((name) => !seen.valueSeen.has(name))),
24793
+ value: seen.valueSeen
24794
+ };
24547
24795
  }
24548
24796
  //#endregion
24549
24797
  //#region src/actions/api-exposure/analyzer/program.ts
@@ -24656,35 +24904,48 @@ function typesAliasesOf(target) {
24656
24904
  return target.startsWith("@") ? [`@types/${target.slice(1).replace("/", "__")}`] : [`@types/${target}`];
24657
24905
  }
24658
24906
  /**
24659
- * True when `target` is provided by the dependency closure of one of the
24660
- * package's declared deps (depth-limited, mirroring the peer-chain walk).
24661
- * An exposed-but-unlisted package that arrives this way is version-managed
24662
- * by the declaring intermediary, so the analyzer must not conclude `peer`
24663
- * on its own — the emitted d.ts (deplint's dist type-import rule) is the
24664
- * enforcement point for whether it must also be declared here.
24907
+ * Resolves a provider package's real directory and its declared runtime
24908
+ * dependencies. The realpath matters under pnpm's non-hoisted layout: a
24909
+ * provider's own dependencies are only resolvable from its virtual-store
24910
+ * directory, not from the workspace that (transitively) links it.
24665
24911
  */
24666
- function readDeclaredDependencies(workspaceDir, dep) {
24667
- const manifestPath = findDepPackageJson(workspaceDir, dep);
24668
- if (manifestPath === void 0) return [];
24912
+ function resolveProvider(baseDir, dep) {
24913
+ const manifestPath = findDepPackageJson(baseDir, dep);
24914
+ if (manifestPath === void 0) return void 0;
24669
24915
  try {
24670
24916
  const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
24671
- return Object.keys(manifest.dependencies ?? {});
24917
+ let dir = PATH.dirname(manifestPath);
24918
+ try {
24919
+ dir = fs.realpathSync(dir);
24920
+ } catch {}
24921
+ return {
24922
+ dependencies: Object.keys(manifest.dependencies ?? {}),
24923
+ dir
24924
+ };
24672
24925
  } catch {
24673
- return [];
24926
+ return;
24674
24927
  }
24675
24928
  }
24676
24929
  function isProvidedByDeclaredDeps(workspaceDir, declared, targets) {
24677
24930
  const targetSet = new Set(targets);
24678
24931
  const visited = /* @__PURE__ */ new Set();
24679
- let frontier = [...declared];
24932
+ let frontier = [...declared].map((name) => ({
24933
+ baseDir: workspaceDir,
24934
+ name
24935
+ }));
24680
24936
  for (let depth = 0; depth <= PROVIDED_CLOSURE_DEPTH; depth++) {
24681
- const unvisited = frontier.filter((entry) => !visited.has(entry));
24682
24937
  const next = [];
24683
- for (const dep of unvisited) {
24684
- visited.add(dep);
24685
- const dependencies = readDeclaredDependencies(workspaceDir, dep);
24686
- if (dependencies.some((dependency) => targetSet.has(dependency))) return true;
24687
- next.push(...dependencies);
24938
+ const unvisited = frontier.filter(({ name }) => !visited.has(name));
24939
+ for (const { baseDir, name } of unvisited) {
24940
+ visited.add(name);
24941
+ const provider = resolveProvider(baseDir, name);
24942
+ if (provider !== void 0) {
24943
+ if (provider.dependencies.some((dependency) => targetSet.has(dependency))) return true;
24944
+ next.push(...provider.dependencies.map((dependency) => ({
24945
+ baseDir: provider.dir,
24946
+ name: dependency
24947
+ })));
24948
+ }
24688
24949
  }
24689
24950
  frontier = next;
24690
24951
  }
@@ -24695,25 +24956,80 @@ function requiredPeerEvidence(sources) {
24695
24956
  const chains = [...new Set(sources.map((source) => source.chain?.join(" > ") ?? source.requiredBy))];
24696
24957
  return `required as a peer by ${chains.slice(0, 3).join(", ")}${chains.length > 3 ? ` (+${chains.length - 3} more)` : ""}`;
24697
24958
  }
24959
+ /**
24960
+ * Exposure evidence for the `'when-exposed'` forwarding policy: any enabled
24961
+ * exposure-rule finding means the dependency's types are part of this
24962
+ * package's public contract, so consumers interact with the dependency.
24963
+ */
24964
+ function hasEnabledExposure(raw, dependency, config) {
24965
+ return raw.some((finding) => finding.ruleId.startsWith("aei.exposure.") && config.ruleFor(finding.ruleId, dependency)?.enabled === true);
24966
+ }
24967
+ /**
24968
+ * The distinct chain roots when every chain imposing the peer contract is
24969
+ * rooted at a package this one imports exclusively as types — such chains
24970
+ * never execute at runtime here. Undefined when any root is (or may be)
24971
+ * a runtime import.
24972
+ */
24973
+ function typeOnlyChainRoots(peerSources, importedPackages) {
24974
+ if (importedPackages === void 0) return void 0;
24975
+ const roots = [...new Set(peerSources.map((source) => source.chain?.[0] ?? source.requiredBy))];
24976
+ return roots.every((root) => importedPackages.typeOnly.has(root)) ? roots : void 0;
24977
+ }
24978
+ /**
24979
+ * Resolves an unmet chain peer contract to a finding under the configured
24980
+ * forwarding policy (spec sections 6/8). Conclusive forwarding
24981
+ * (`aei.signal.required-peer`, ∞) applies under `'always'`, whenever usage
24982
+ * is unknown (no program), or when the policy's own-usage/exposure test
24983
+ * passes. Exposure is conclusive in both evidence-based modes — a peer
24984
+ * whose types reach this package's public API (e.g. through a re-exported
24985
+ * workspace-internal surface) is part of its contract even when this
24986
+ * package's own files never import it. Otherwise the contract downgrades
24987
+ * to the informational rule that best explains why no forwarding is
24988
+ * required here.
24989
+ */
24990
+ function peerChainFinding({ config, dependency, hasExposure, importedPackages, peerSources }) {
24991
+ const evidence = requiredPeerEvidence(peerSources);
24992
+ const file = "(peer-chain)";
24993
+ const valueImported = importedPackages?.value.has(dependency) ?? false;
24994
+ const typeImported = importedPackages?.typeOnly.has(dependency) ?? false;
24995
+ if (config.peerForwarding === "always" || importedPackages === void 0 || hasExposure || valueImported || config.peerForwarding === "when-used" && typeImported) return {
24996
+ dependency,
24997
+ evidence,
24998
+ file,
24999
+ ruleId: "aei.signal.required-peer"
25000
+ };
25001
+ const typeOnlyRoots = typeOnlyChainRoots(peerSources, importedPackages);
25002
+ if (typeOnlyRoots !== void 0) return {
25003
+ dependency,
25004
+ evidence: `${evidence} — but ${typeOnlyRoots.length === 1 ? `${typeOnlyRoots[0]} is imported only as types here` : `${typeOnlyRoots.join(", ")} are imported only as types here`}; the chain never executes at runtime, so there is no contract to forward`,
25005
+ file,
25006
+ ruleId: "aei.signal.type-only-chain-peer"
25007
+ };
25008
+ if (config.peerForwarding === "when-exposed") return {
25009
+ dependency,
25010
+ evidence: `${evidence} — neither exposed through this package's API nor value-imported; declaring it in this package's own dependencies (the provider pattern) discharges the contract (peerForwarding: when-exposed)`,
25011
+ file,
25012
+ ruleId: "aei.signal.absorbable-peer"
25013
+ };
25014
+ return {
25015
+ dependency,
25016
+ evidence: `${evidence} — neither imported nor exposed here; the installer resolves the contract (peerForwarding: when-used)`,
25017
+ file,
25018
+ ruleId: "aei.signal.inherited-peer"
25019
+ };
25020
+ }
24698
25021
  function assessDependency({ config, dependency, importedPackages, isSelfOrInternal, isTerminal, raw, refTypes, requiredPeerSources, sections, workspaceDir }) {
24699
25022
  const dependencyRaw = raw.filter((finding) => finding.dependency === dependency);
24700
25023
  const signals = getDependencySignals(workspaceDir, dependency);
24701
25024
  if (signals !== void 0) dependencyRaw.push(...signals.findings);
24702
25025
  const peerSources = requiredPeerSources.get(dependency);
24703
- if (peerSources !== void 0 && !isSelfOrInternal(dependency) && !sections.dependencies.has(dependency)) {
24704
- const isForwarded = config.peerForwarding === "always" || importedPackages === void 0 || importedPackages.has(dependency);
24705
- dependencyRaw.push(isForwarded ? {
24706
- dependency,
24707
- evidence: requiredPeerEvidence(peerSources),
24708
- file: "(peer-chain)",
24709
- ruleId: "aei.signal.required-peer"
24710
- } : {
24711
- dependency,
24712
- evidence: `${requiredPeerEvidence(peerSources)} — never imported here; the installer resolves the contract (peerForwarding: when-used)`,
24713
- file: "(peer-chain)",
24714
- ruleId: "aei.signal.inherited-peer"
24715
- });
24716
- }
25026
+ if (peerSources !== void 0 && !isSelfOrInternal(dependency) && !sections.dependencies.has(dependency)) dependencyRaw.push(peerChainFinding({
25027
+ config,
25028
+ dependency,
25029
+ hasExposure: hasEnabledExposure(dependencyRaw, dependency, config),
25030
+ importedPackages,
25031
+ peerSources
25032
+ }));
24717
25033
  if (config.treeShaking && sections.sideEffectsFree && signals?.esm === true && hasInstalledVersionMultiplicity(workspaceDir, dependency)) dependencyRaw.push({
24718
25034
  dependency,
24719
25035
  evidence: "sideEffects: false package with ESM dependency installed at multiple versions — peers improve deduplication",
@@ -24773,7 +25089,7 @@ function isProvidedBySections(dependency, findings, sections, workspaceDir) {
24773
25089
  */
24774
25090
  function resolveRecommendation(scored, findings, { config, dependency, isSelfOrInternal, isTerminal, refTypes, sections, workspaceDir }) {
24775
25091
  const classification = config.classificationFor(dependency) ?? refTypes?.get(dependency);
24776
- if (classification !== void 0) return [classification === "peer" ? "peer" : "dependency", "override"];
25092
+ if (classification !== void 0 && !(isTerminal === true && classification === "peer")) return [classification === "peer" ? "peer" : "dependency", "override"];
24777
25093
  if (isTerminal === true) {
24778
25094
  if (sections.isPrivate && currentSectionOf(dependency, sections) === "devDependencies") return void 0;
24779
25095
  return ["dependency", "terminal"];
@@ -24795,7 +25111,7 @@ function analyzeWorkspaceApiExposure({ cache, config, isTerminal, refTypes, work
24795
25111
  const requiredPeerSources = getRuntimeRootedNonOptionalTransitivePeerSources(workspaceDir, getDependenciesFromPackageJson(PATH.join(workspaceDir, "package.json")), { excludeSatisfiedInChain: true });
24796
25112
  const entryPoints = resolveEntryPoints(workspaceDir);
24797
25113
  const program = createExposureProgram(workspaceDir, entryPoints, cache);
24798
- const importedPackages = program === void 0 || config.peerForwarding !== "when-used" ? void 0 : getImportedPackages(program, workspaceDir);
25114
+ const importedPackages = program === void 0 || config.peerForwarding === "always" ? void 0 : getImportedPackages(program, workspaceDir);
24799
25115
  const raw = [];
24800
25116
  if (program !== void 0) raw.push(...getExposureFindings({
24801
25117
  entryFiles: entryPoints,
@@ -25206,38 +25522,6 @@ function analyzeBarrel(barrelPkg, fromDir, scopePrefix) {
25206
25522
  return [...collected].toSorted((a, b) => a.localeCompare(b));
25207
25523
  }
25208
25524
  //#endregion
25209
- //#region src/actions/deplint/sourceFileCache.ts
25210
- const cache$2 = /* @__PURE__ */ new Map();
25211
- function scriptKindForPath(filePath) {
25212
- if (/\.(?:mjs|cjs|js)$/i.test(filePath)) return ts.ScriptKind.JS;
25213
- if (/\.tsx$/i.test(filePath)) return ts.ScriptKind.TSX;
25214
- if (/\.jsx$/i.test(filePath)) return ts.ScriptKind.JSX;
25215
- }
25216
- function getCachedSourceFile(filePath) {
25217
- const cached = cache$2.get(filePath);
25218
- if (cached !== void 0) return cached;
25219
- const sourceCode = fs.readFileSync(filePath, "utf8");
25220
- const entry = {
25221
- sourceCode,
25222
- sourceFile: ts.createSourceFile(PATH.basename(filePath), sourceCode, ts.ScriptTarget.Latest, true, scriptKindForPath(filePath))
25223
- };
25224
- cache$2.set(filePath, entry);
25225
- return entry;
25226
- }
25227
- /** Like getCachedSourceFile, but returns undefined when the file cannot be read. */
25228
- function tryGetCachedSourceFile(filePath) {
25229
- const cached = cache$2.get(filePath);
25230
- if (cached !== void 0) return cached;
25231
- try {
25232
- return getCachedSourceFile(filePath);
25233
- } catch {
25234
- return;
25235
- }
25236
- }
25237
- function clearSourceFileCache() {
25238
- cache$2.clear();
25239
- }
25240
- //#endregion
25241
25525
  //#region src/actions/deplint/findFiles.ts
25242
25526
  const codeExtensions$1 = "*.{ts,tsx,mts,cts,js,mjs,cjs}";
25243
25527
  const codeExtensionRe = /\.(?:ts|tsx|mts|cts|js|mjs|cjs)$/i;
@@ -27570,56 +27854,6 @@ function getTypesFromTsconfigs(location) {
27570
27854
  return [...packages];
27571
27855
  }
27572
27856
  //#endregion
27573
- //#region src/actions/deplint/getImportsFromFile.ts
27574
- function isTypeOnlyImportClause(clause) {
27575
- if (clause === void 0) return false;
27576
- if ("phaseModifier" in clause) {
27577
- const mod = clause.phaseModifier;
27578
- return (typeof mod === "number" ? mod : mod?.kind) === ts.SyntaxKind.TypeKeyword;
27579
- }
27580
- return clause.isTypeOnly ?? false;
27581
- }
27582
- function getImportsFromFile(filePath, importPaths, typeImportPaths) {
27583
- const { sourceFile } = getCachedSourceFile(filePath);
27584
- const imports = [];
27585
- const typeImports = [];
27586
- const isDeclarationFile = filePath.endsWith(".d.ts") || filePath.endsWith(".d.mts") || filePath.endsWith(".d.cts");
27587
- function visit(node) {
27588
- if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
27589
- const moduleSpecifier = node.moduleSpecifier?.getFullText();
27590
- const isTypeImport = ts.isImportDeclaration(node) ? isTypeOnlyImportClause(node.importClause) : false;
27591
- if (typeof moduleSpecifier === "string") {
27592
- const trimmed = moduleSpecifier.replaceAll(/['"]/g, "").trim();
27593
- if (isTypeImport || isDeclarationFile) typeImports.push(trimmed);
27594
- else imports.push(trimmed);
27595
- }
27596
- } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
27597
- const [arg] = node.arguments;
27598
- if (ts.isStringLiteral(arg)) imports.push(arg.text);
27599
- } else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "require" && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) imports.push(node.arguments[0].text);
27600
- ts.forEachChild(node, visit);
27601
- }
27602
- visit(sourceFile);
27603
- for (const ref of sourceFile.typeReferenceDirectives) typeImports.push(ref.fileName);
27604
- const importsStartsWithExcludes = [
27605
- ".",
27606
- "#",
27607
- "node:"
27608
- ];
27609
- const isValidImport = (imp) => importsStartsWithExcludes.every((exc) => !imp.startsWith(exc)) && !imp.includes("*") && !imp.includes("!");
27610
- const cleanedImports = imports.filter(isValidImport).map(getBasePackageName);
27611
- const cleanedTypeImports = typeImports.filter(isValidImport).map(getBasePackageName);
27612
- for (const imp of cleanedImports) {
27613
- importPaths[imp] ??= [];
27614
- importPaths[imp].push(filePath);
27615
- }
27616
- for (const imp of cleanedTypeImports) {
27617
- typeImportPaths[imp] ??= [];
27618
- typeImportPaths[imp].push(filePath);
27619
- }
27620
- return [cleanedImports, cleanedTypeImports];
27621
- }
27622
- //#endregion
27623
27857
  //#region src/actions/deplint/getStorybookConfigImports.ts
27624
27858
  const storybookMainPattern = /(?:^|[\\/])\.storybook[\\/]main\.[cm]?[jt]sx?$/;
27625
27859
  const npmPackageNamePattern = /^@?[a-z0-9][\w./-]*$/i;
@@ -30107,6 +30341,80 @@ async function loadDeplintRules(config) {
30107
30341
  return normalizeDeplintRules(plugins.flatMap((plugin) => plugin.rules), config, new Set(builtInDeplintPlugin.rules.map((rule) => rule.id)));
30108
30342
  }
30109
30343
  //#endregion
30344
+ //#region src/actions/deplint/getInternalSurfaceVouchedPeers.ts
30345
+ /** Bound on recursion through nested workspace-internal surfaces. */
30346
+ const MAX_INTERNAL_SURFACE_DEPTH = 3;
30347
+ const surfaceImportsCache = /* @__PURE__ */ new Map();
30348
+ function resolveInternalSurface(baseDir, name) {
30349
+ const manifestPath = findDepPackageJson(baseDir, name);
30350
+ if (manifestPath === void 0) return void 0;
30351
+ try {
30352
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
30353
+ let dir = PATH.dirname(manifestPath);
30354
+ try {
30355
+ dir = fs.realpathSync(dir);
30356
+ } catch {}
30357
+ return {
30358
+ dir,
30359
+ peerDependencies: Object.keys(manifest.peerDependencies ?? {})
30360
+ };
30361
+ } catch {
30362
+ return;
30363
+ }
30364
+ }
30365
+ /**
30366
+ * External package names referenced by a package's shipped surface: import
30367
+ * specifiers in its dist runtime and emitted d.ts. Falls back to src when
30368
+ * no dist exists (unbuilt workspace), mirroring deplint's own fallback.
30369
+ */
30370
+ function getSurfaceImports(dir) {
30371
+ const cached = surfaceImportsCache.get(dir);
30372
+ if (cached !== void 0) return cached;
30373
+ let files = findFilesByGlob(dir, "dist/**/*.{js,mjs,cjs,ts,mts,cts}", ["**/node_modules/**"]);
30374
+ if (files.length === 0) files = findFilesByGlob(dir, "src/**/*.{ts,tsx,mts,cts}", ["**/node_modules/**"]);
30375
+ const imports = /* @__PURE__ */ new Set();
30376
+ for (const file of files) {
30377
+ const [valueImports, typeImports] = getImportsFromFile(file, {}, {});
30378
+ for (const name of valueImports) imports.add(name);
30379
+ for (const name of typeImports) imports.add(name);
30380
+ }
30381
+ surfaceImportsCache.set(dir, imports);
30382
+ return imports;
30383
+ }
30384
+ /**
30385
+ * Peers vouched for by workspace-internal packages whose surface this
30386
+ * package ships. A pure re-export barrel never names the peers it
30387
+ * re-exposes in its own imports or emitted d.ts, so scan-based forwarding
30388
+ * evidence (`PeerForwardingPolicy.importedModules`) cannot see them. The
30389
+ * re-exported internal package's own shipped surface is the next-best
30390
+ * authority: any peer it declares AND references from its dist runtime or
30391
+ * emitted d.ts flows through every package that ships its surface.
30392
+ * Recurses through nested internal surfaces (a barrel re-exporting a
30393
+ * facade re-exporting core), depth-limited.
30394
+ */
30395
+ function getInternalSurfaceVouchedPeers(location, shippedImports, workspaceNames) {
30396
+ const vouched = /* @__PURE__ */ new Set();
30397
+ const visited = /* @__PURE__ */ new Set();
30398
+ const visitSurface = ({ baseDir, name }) => {
30399
+ if (visited.has(name)) return [];
30400
+ visited.add(name);
30401
+ const surface = resolveInternalSurface(baseDir, name);
30402
+ if (surface === void 0) return [];
30403
+ const surfaceImports = getSurfaceImports(surface.dir);
30404
+ for (const peer of surface.peerDependencies) if (surfaceImports.has(peer)) vouched.add(peer);
30405
+ return [...surfaceImports].filter((imported) => workspaceNames.has(imported)).map((imported) => ({
30406
+ baseDir: surface.dir,
30407
+ name: imported
30408
+ }));
30409
+ };
30410
+ let frontier = [...new Set(shippedImports)].filter((name) => workspaceNames.has(name)).map((name) => ({
30411
+ baseDir: location,
30412
+ name
30413
+ }));
30414
+ for (let depth = 0; depth < MAX_INTERNAL_SURFACE_DEPTH && frontier.length > 0; depth++) frontier = frontier.flatMap((ref) => visitSurface(ref));
30415
+ return vouched;
30416
+ }
30417
+ //#endregion
30110
30418
  //#region src/actions/deplint/snapshot.ts
30111
30419
  function buildUnusedDependencyExclude(options, requiredTransitivePeers) {
30112
30420
  return /* @__PURE__ */ new Set([
@@ -30183,14 +30491,16 @@ function buildWorkspaceContext(workspace, options = {}) {
30183
30491
  const packageMetaStarted = performance.now();
30184
30492
  const packageJsonPath = `${workspace.location}/package.json`;
30185
30493
  const packageParams = getDependenciesFromPackageJson(packageJsonPath);
30186
- const peerForwarding = options.classifier === "aei" && options.apiExposureConfig?.peerForwarding === "when-used" ? {
30187
- importedModules: /* @__PURE__ */ new Set([
30494
+ const forwardingMode = options.classifier === "aei" ? options.apiExposureConfig?.peerForwarding ?? "always" : "always";
30495
+ const peerForwarding = forwardingMode === "always" ? void 0 : {
30496
+ importedModules: forwardingMode === "when-exposed" ? /* @__PURE__ */ new Set([...sourceParams.externalDistImports, ...sourceParams.externalDistTypeImports]) : /* @__PURE__ */ new Set([
30188
30497
  ...sourceParams.externalAllImports,
30189
30498
  ...sourceParams.externalDistImports,
30190
30499
  ...sourceParams.externalDistTypeImports
30191
30500
  ]),
30192
- mode: "when-used"
30193
- } : void 0;
30501
+ mode: forwardingMode,
30502
+ vouchedPeers: options.workspaceNames === void 0 ? void 0 : getInternalSurfaceVouchedPeers(workspace.location, [...sourceParams.externalDistImports, ...sourceParams.externalDistTypeImports], options.workspaceNames)
30503
+ };
30194
30504
  const requiredTransitivePeers = getRequiredNonOptionalTransitivePeers(workspace.location, packageParams);
30195
30505
  const runtimeRootedRequired = new Set([...getRuntimeRootedNonOptionalTransitivePeers(workspace.location, packageParams)].filter((peer) => isPeerForwarded(peerForwarding, peer)));
30196
30506
  const packageClassification = classifyDeplintPackage(workspace.location, terminalOverride);