Repository navigation
Expand file tree
/
Copy pathpackage-boundaries.ts
More file actions
604 lines (578 loc) · 26.4 KB
/
Copy pathpackage-boundaries.ts
File metadata and controls
604 lines (578 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// Catches: a package importing a workspace sibling its manifest never declared, and a root
// file tunnelling into a package's src with a relative path — both for every file, compiled
// or not — plus the whole specifier sweep (unknown package, un-exported subpath) for the
// scripts/ files the type graph omits. `tsc -b` owns the rest of the old R11 surface for
// compiled sources: NodeNext resolution rejects a non-exported subpath and an unknown
// package (TS2307), and composite `rootDir` rejects a package→root relative escape
// (TS6059 + TS6307) — planted proofs recorded on #3279.
// Evidence: 76453add71 (#1494, #1490 W0) established the workspace split this rule protects;
// 83322a3f2f (#1574) pinned exact facade symbols for every workspace package; #3279 moved the
// type-check onto `tsc -b` project references and retired the checks it now enforces.
// Cost: 510 LOC (rule) + 998 LOC (test).
// Kill criterion: retire a remaining branch only when something owns its mechanism, not merely
// its symptom. An undeclared `workspace:*` sibling is type-clean and runtime-green INSIDE
// this repo because pnpm links every workspace package under the root `node_modules` — the
// declaration is what the published bundle externalizes against, so no compiler check can
// express it here (planted in #3279: `tsc -b` accepted it). A relative root→package tunnel
// typechecks too; its failure is the runtime double instantiation this rule names.
//
// R11 package-boundaries: the workspace rules of #1490, as data the gate walks.
//
// What remains is exactly what the type graph cannot see:
// a package import of a sibling the manifest never declared (pnpm's root links make it resolve
// anyway), a root file tunnelling into `packages/*/src` with a relative path (tsc typechecks
// it fine; Node's ESM loader does not realpath specifiers, so a module loaded BOTH relatively
// and via its package specifier instantiates twice in one process — duplicate AppError, broken
// instanceof), and, for `scripts/` files which sit outside the type graph by design, the
// root-side unknown-package and exports-map checks that compiled files get from TS2307.
// The consumer half of R83 (production code importing a test-only export or test-kit) is checked at
// the same import sites, so the one specifier walk serves both rules.
import fs from 'node:fs';
import path from 'node:path';
import { parseImports, resolveWorkspaceSpecifier } from './model.ts';
import {
PACKAGE_EXPORT_SURFACE_RULE,
readExportManifests,
resolveAllConditionTargets,
testOnlyImportMessage,
} from './package-export-surface.ts';
import {
isProductionSourceFile,
listTrackedPackageManifests,
listTrackedProductionSources,
} from './tracked-sources.ts';
export type PackageBoundaryViolation = {
rule: string;
file: string;
line: number;
message: string;
};
export type WorkspacePackage = {
/** Repo-relative package dir, e.g. `packages/kernel`. */
dir: string;
name: string;
/** Full import specifier -> repo-relative source target, from `exports`. */
exportTargets: ReadonlyMap<string, string>;
/** Export key -> every condition target (`types`, `import`, `default`, ...), repo-relative. */
exportConditionTargets?: ReadonlyMap<string, readonly string[]>;
/** Declared `workspace:*` dependencies on sibling internal packages. */
workspaceDependencies: ReadonlySet<string>;
/**
* Workspace siblings a private package declares in `devDependencies`. Only test support (tests,
* fixtures, test trees) may import through them; production source still needs
* `workspaceDependencyField`. A published package keeps every sibling in `devDependencies`
* already, so this is empty there.
*/
workspaceDevDependencies?: ReadonlySet<string>;
/** Where siblings are declared: a published package bundles them, so it lists them as dev-only. */
workspaceDependencyField: 'dependencies' | 'devDependencies';
/** Non-workspace dependencies that the root build must externalize. */
externalDependencies: ReadonlyMap<string, string>;
};
export type SpecifierSite = {
file: string;
line: number;
specifier: string;
};
/**
* Every import specifier in `source`, with its 1-based line — through the
* layering model's own parser, so static/dynamic/side-effect/re-export sites
* and both quote styles are covered by one scanner instead of a private regex
* that silently missed double-quoted routes.
*
* `vi.mock`/`vi.doMock`/`vi.mockActual`/`vi.unmock`/`vi.importActual` join the sweep
* by literal scan: they are plain call expressions the AST import parser never
* visits, yet the loader resolves their specifier and instantiates that module under
* test — the same double-instance route a relative tunnel takes. `importOriginal
* <typeof import('...')>` needs no extra branch; the parser already sees it as a
* TSImportType.
*/
const VI_MOCK_CALL_RE =
/\bvi\.(?:mock|doMock|mockActual|unmock|importActual)\(\s*(['"])([^'"\n]*)\1/g;
export function specifierSites(file: string, source: string): SpecifierSite[] {
const sites: SpecifierSite[] = parseImports(source).map((edge) => ({
file,
line: edge.line,
specifier: edge.spec,
}));
for (const match of source.matchAll(VI_MOCK_CALL_RE)) {
const line = source.slice(0, match.index).split('\n').length;
const specifier = match[2]!;
if (!sites.some((site) => site.line === line && site.specifier === specifier))
sites.push({ file, line, specifier });
}
return sites.sort((a, b) => a.line - b.line);
}
/**
* Every workspace package a gate may reason about, read from TRACKED manifests only.
*
* A `readdirSync` of `packages/` would also pick up a directory a contributor created but never
* committed, and its `exports` map would then contribute entry surfaces to R11 and to the
* ADR-0019 loading-shape budgets -- gates whose whole claim is that they describe committed state
* (#1965 review). R13's `readTrackedPlatformPackageDeclarations` already enumerated its manifests
* this way; this closes the same hole for every workspace package, at the source rather than by
* filtering the output.
*/
export function readWorkspacePackages(repoRoot: string): WorkspacePackage[] {
return workspacePackagesFromManifests(readTrackedPackageManifests(repoRoot));
}
/** Tracked workspace package manifests, text keyed by repo-relative path. */
export function readTrackedPackageManifests(repoRoot: string): Map<string, string> {
return new Map(
listTrackedPackageManifests(repoRoot).map((manifestFile) => [
manifestFile,
fs.readFileSync(path.join(repoRoot, manifestFile), 'utf8'),
]),
);
}
/** The same package model over manifest sources already in hand, e.g. read from a git ref. */
export function workspacePackagesFromManifests(
manifests: ReadonlyMap<string, string>,
): WorkspacePackage[] {
const packages: WorkspacePackage[] = [];
for (const manifestFile of [...manifests.keys()].sort()) {
const entry = path.posix.basename(path.posix.dirname(manifestFile));
const manifest = JSON.parse(manifests.get(manifestFile)!) as {
name?: string;
private?: boolean;
exports?: Record<string, { default?: string; import?: string } | string>;
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
};
if (!manifest.name) continue;
const exportTargets = new Map<string, string>();
for (const [subpath, target] of Object.entries(manifest.exports ?? {})) {
const targetFile = typeof target === 'string' ? target : (target.default ?? target.import);
if (!targetFile) continue;
exportTargets.set(
path.posix.join(manifest.name, subpath),
path.posix.join('packages', entry, path.posix.normalize(targetFile)),
);
}
const conditionTargets = new Map(
readExportManifests(new Map([[manifestFile, manifests.get(manifestFile)!]])).flatMap(
(declared) =>
declared.exports.map(
({ key, targets }) =>
[
path.posix.join(manifest.name!, key),
targets.map((target) =>
path.posix.join('packages', entry, path.posix.normalize(target)),
),
] as const,
),
),
);
const workspaceDependencyField = manifest.private === true ? 'dependencies' : 'devDependencies';
const workspaceDependencies = new Set(
Object.entries(manifest[workspaceDependencyField] ?? {})
.filter(([, range]) => range.startsWith('workspace:'))
.map(([name]) => name),
);
const workspaceDevDependencies = new Set(
manifest.private === true
? Object.entries(manifest.devDependencies ?? {})
.filter(([, range]) => range.startsWith('workspace:'))
.map(([name]) => name)
: [],
);
const externalDependencies = new Map(
Object.entries(manifest.dependencies ?? {}).filter(
([, range]) => !range.startsWith('workspace:'),
),
);
packages.push({
dir: `packages/${entry}`,
name: manifest.name,
exportTargets,
exportConditionTargets: conditionTargets,
workspaceDependencies,
workspaceDevDependencies,
workspaceDependencyField,
externalDependencies,
});
}
return packages;
}
function packageByName(packages: readonly WorkspacePackage[], name: string) {
return packages.find((pkg) => pkg.name === name);
}
/**
* A specifier is named by the exports map when it matches a named key or resolves
* through a `*` pattern entry. Delegates to `resolveWorkspaceSpecifier` so every
* consumer (this rule, the layering edges, the depgraph, mutation ownership, and
* the Stryker alias table) applies one Node-exports semantics, not a private scan.
*/
function namedByExports(target: WorkspacePackage, specifier: string): boolean {
return resolveWorkspaceSpecifier(specifier, target.exportTargets) !== undefined;
}
/**
* R83's consumer half (see package-export-surface.ts): a production file importing a test-only
* export, or the private test-kit package, is production code depending on a test double — it
* must use a production subpath or inject the real port.
*/
function checkTestOnlyImportSite(
site: SpecifierSite,
target: WorkspacePackage,
): PackageBoundaryViolation | undefined {
const resolvedTargets = resolveAllConditionTargets(
site.specifier,
target.exportConditionTargets ??
new Map([...target.exportTargets].map(([key, file]) => [key, [file]])),
);
const message = testOnlyImportMessage(
site.file,
site.specifier,
target.name,
resolvedTargets.length > 0 ? resolvedTargets : undefined,
);
if (message === undefined) return undefined;
return { rule: PACKAGE_EXPORT_SURFACE_RULE, file: site.file, line: site.line, message };
}
function specifierPackageName(specifier: string): string | undefined {
const match = /^(@[^/]+\/[^/]+)/.exec(specifier);
return match?.[1];
}
/**
* The file set R11 treats as parsed by the `tsc -b` graph: each package project includes its
* own `src/`, and the root project includes `src/` and `test/`. Everything else the R11 walk
* visits — the rest of `scripts/` (gate and tooling modules run through
* `--experimental-strip-types`, not a tsconfig program), the `packages/maestro/test/`
* conformance harness, and package build configs — reaches packages through import sites the
* compiler never parses, so R11 stays the only owner of every boundary claim about those
* routes (#3279). Only the RESOLUTION branches (unknown package, un-exported subpath) are
* split this way; the relative-escape branch fires regardless — a planted sibling tunnel
* `tsc -b` accepted, see `checkPackageInternalSites`.
*
* One documented divergence: the root program also includes
* `scripts/help-conformance-command-validator.ts`, which this predicate classifies as
* uncompiled. That is fail-closed — R11 keeps its full branch set (unknown package,
* exports-map) for the file on top of what tsc enforces — never fail-open. The divergence
* and the exact root include list are pinned in `project-references.test.ts`, and the
* per-package `include: ["src"]` / no-`exclude` shape this predicate's regexes assume is
* pinned there too, so widening any project's file set must be recorded there rather than
* silently diverging from this predicate.
*/
export function insideCompiledSources(file: string): boolean {
return /^packages\/[^/]+\/src\//.test(file) || /^src\//.test(file) || /^test\//.test(file);
}
/**
* A sibling import must be declared `workspace:*` in the package manifest. Production source needs
* the production field (`dependencies`, or `devDependencies` for a published package, which
* bundles its siblings); test support — tests, `*.fixtures.*` files, test trees, test-kit — may
* also resolve through a private package's `devDependencies`, so a test-only sibling such as
* test-kit never ships as a runtime dependency.
*/
function undeclaredSiblingMessage(
pkg: WorkspacePackage,
name: string,
site: SpecifierSite,
): string | undefined {
if (name === pkg.name || pkg.workspaceDependencies.has(name)) return undefined;
const declaredForTests = pkg.workspaceDevDependencies?.has(name) ?? false;
if (declaredForTests && !isProductionSourceFile(site.file)) return undefined;
return declaredForTests
? `${pkg.name} imports '${site.specifier}' from production source, but ${pkg.dir}/package.json ` +
`declares "${name}" only in devDependencies: declare it in ${pkg.workspaceDependencyField} ` +
`or import it from test support only.`
: `${pkg.name} imports '${site.specifier}' without declaring "${name}": "workspace:*" ` +
`in ${pkg.dir}/package.json ${pkg.workspaceDependencyField}.`;
}
/**
* Rules for files INSIDE a package. An undeclared sibling import is R11's alone: pnpm links
* every workspace package under the root `node_modules`, so the import resolves, compiles, and
* runs in this repo even when the manifest never declares it — and a published bundle
* externalizes against that declaration. The relative escape past the package dir is R11's
* too, compiled or not: a planted `pnpm exec tsc -b packages/host-kit --force` with
* `import { AppError } from '../../kernel/src/errors.ts'` in `host-kit/src/` **exits 0** —
* the redirect to kernel's `dist-types` keeps every emitted file under host-kit's `rootDir`,
* so neither TS6059 nor TS6307 fires (the root-escape tunnel DOES fail: TS2307, since `../..
* /../kernel/...` lands outside every include and no package owns `kernel` at that depth).
* What the sibling tunnel risks is runtime identity: Node's ESM loader does not realpath
* specifiers, so when the same module is ALSO loaded through its package specifier — the
* normal route for every other consumer — the two keys instantiate it twice in one process
* (duplicate AppError, broken `instanceof`). Type-only tunnels carry no runtime cost, but
* the branch cannot condition on that from syntax alone and the layering claim fails either
* way. Any duplicate-instance risk invisible to the compiler is R11's to hold; the
* remaining resolution failures (unknown package, subpath the exports map does not name)
* are owned by NodeNext for compiled files with TS2307; uncompiled files never reach either
* check, so for them R11 holds every branch.
*/
export function checkPackageInternalSites(
pkg: WorkspacePackage,
sites: readonly SpecifierSite[],
allPackages: readonly WorkspacePackage[],
compiled: boolean,
): PackageBoundaryViolation[] {
const violations: PackageBoundaryViolation[] = [];
for (const site of sites) {
if (site.specifier.startsWith('.')) {
const resolved = path.posix.normalize(
path.posix.join(path.posix.dirname(site.file), site.specifier),
);
if (!resolved.startsWith(`${pkg.dir}/`)) {
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message:
`'${site.specifier}' escapes ${pkg.dir}/ — a workspace package may not reach ` +
`outside its own directory. Import a sibling through its specifier (mixing the ` +
`two routes instantiates the module twice), or move the shared code below ` +
`${pkg.dir}.`,
});
}
continue;
}
const name = specifierPackageName(site.specifier);
if (!name || !name.startsWith('@agent-device/')) continue;
const target = packageByName(allPackages, name);
if (!target) {
if (!compiled) {
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message: `'${site.specifier}' names an unknown workspace package.`,
});
}
continue;
}
const undeclared = undeclaredSiblingMessage(pkg, name, site);
if (undeclared) {
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message: undeclared,
});
}
const testDataOnly = checkTestOnlyImportSite(site, target);
if (testDataOnly) {
violations.push(testDataOnly);
continue;
}
if (!compiled && !namedByExports(target, site.specifier)) {
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message:
`'${site.specifier}' is not named by ${target.dir}/package.json#exports — import an ` +
`exported subpath or earn a new one with a real consumer.`,
});
}
}
return violations;
}
/**
* Rules for files OUTSIDE packages/ (src, test, scripts). Two claims remain R11's own for every
* root file: the relative tunnel into a packages/<name>/src directory — the compiler typechecks
* such an import
* fine (#3279), but Node's ESM loader does not realpath specifiers, so dual relative/specifier
* loads instantiate the module twice — and a workspace specifier the root manifest never
* declares, which the root's own link farm resolves anyway. For compiled root files the
* compiler owns unknown packages and un-exported subpaths with TS2307; for scripts/ files,
* which sit outside the type graph by design, R11 keeps every branch.
*/
export function checkRootSites(
sites: readonly SpecifierSite[],
packages: readonly WorkspacePackage[],
rootWorkspaceDependencies: ReadonlySet<string>,
compiled: boolean,
): PackageBoundaryViolation[] {
const violations: PackageBoundaryViolation[] = [];
for (const site of sites) {
if (site.specifier.startsWith('.')) {
const resolved = path.posix.normalize(
path.posix.join(path.posix.dirname(site.file), site.specifier),
);
if (!/^packages\/[^/]+\//.test(resolved)) continue;
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message:
`'${site.specifier}' bypasses the package boundary — import the package specifier ` +
`instead, or dual specifier/relative loads instantiate the module twice.`,
});
continue;
}
const name = specifierPackageName(site.specifier);
if (!name || !name.startsWith('@agent-device/')) continue;
const target = packageByName(packages, name);
if (!target) {
if (!compiled) {
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message: `'${site.specifier}' names an unknown workspace package.`,
});
}
continue;
}
if (!rootWorkspaceDependencies.has(name)) {
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message:
`'${site.specifier}' is used but "${name}" is not a "workspace:*" entry in the root ` +
`package.json devDependencies.`,
});
}
const testDataOnly = checkTestOnlyImportSite(site, target);
if (testDataOnly) {
violations.push(testDataOnly);
continue;
}
if (!compiled && !namedByExports(target, site.specifier)) {
violations.push({
rule: 'R11 package-boundaries',
file: site.file,
line: site.line,
message:
`'${site.specifier}' is not named by ${target.dir}/package.json#exports — deep imports ` +
`into package internals are a resolution error; import an exported subpath.`,
});
}
}
return violations;
}
/** Root-manifest `workspace:*` names, from dependencies + devDependencies. */
export function rootWorkspaceDependencyNames(repoRoot: string): Set<string> {
const manifest = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')) as {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
};
return new Set(
Object.entries({ ...manifest.dependencies, ...manifest.devDependencies })
.filter(([, range]) => range.startsWith('workspace:'))
.map(([name]) => name),
);
}
/** Root runtime dependency ranges used by the published bundle. */
export function rootExternalDependencyRanges(repoRoot: string): Map<string, string> {
const manifest = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')) as {
dependencies?: Record<string, string>;
};
return new Map(Object.entries(manifest.dependencies ?? {}));
}
/**
* Every workspace-package entry surface, repo-root-relative and sorted: whatever a package
* manifest's `exports` map points at, plus every production source file under a `src/facades/`
* directory.
*
* The single owner of that question. R11's façade gates and the ADR-0019 eager-closure budget
* table (`scripts/__tests__/eager-closure-budgets.ts`) both consume this, so the two cannot drift
* into disagreeing about what counts as a façade — a gate that scanned a narrower set would
* silently exempt files the other one covers, which is exactly the hole #1960 review found (a
* one-level `readdir` missed both nested façade files and the six `packages/platform-*`
* manifest façades, which have no `facades/` directory at all).
*
* The `src/facades/` side reads TRACKED production sources (`listTrackedProductionSources`), the
* same input every other layering scan uses, and is recursive so a nested façade cannot be
* covered by one gate and missed by another. Tracked-only matters: an uncommitted scratch file
* under a scanned path must stay invisible, or these gates start describing a contributor's
* working directory instead of the committed tree (#1965 review).
*/
export function facadeEntryFiles(repoRoot: string): string[] {
const tracked = new Set(listTrackedProductionSources(repoRoot));
const found = new Set<string>();
// Manifests are already tracked-only, but a tracked manifest's WORKING-TREE content can name a
// target that is not committed yet, so the targets are intersected too. Both origins go through
// the same tracked set: every path this returns is committed, whatever produced it.
for (const pkg of readWorkspacePackages(repoRoot)) {
for (const target of pkg.exportTargets.values()) {
if (tracked.has(target)) found.add(target);
}
}
for (const file of tracked) {
if (file.includes('/src/facades/')) found.add(file);
}
return [...found].filter((file) => fs.existsSync(path.join(repoRoot, file))).sort();
}
function walkTsFiles(repoRoot: string, relativeDir: string): string[] {
const absolute = path.join(repoRoot, relativeDir);
if (!fs.existsSync(absolute)) return [];
const files: string[] = [];
const queue = [absolute];
while (queue.length > 0) {
const dir = queue.pop()!;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name !== 'node_modules' && entry.name !== 'dist-types') queue.push(full);
} else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')) {
files.push(path.relative(repoRoot, full).replaceAll(path.sep, '/'));
}
}
}
return files.sort();
}
/** Flat `specifier -> repo-relative source` map across all workspace packages. */
export function workspaceSpecifierTargets(repoRoot: string): Map<string, string> {
return specifierTargetsOf(readWorkspacePackages(repoRoot));
}
/** The same flat map for a manifest set read elsewhere, e.g. at a git ref. */
export function workspaceSpecifierTargetsFromManifests(
manifests: ReadonlyMap<string, string>,
): Map<string, string> {
return specifierTargetsOf(workspacePackagesFromManifests(manifests));
}
function specifierTargetsOf(packages: readonly WorkspacePackage[]): Map<string, string> {
const targets = new Map<string, string>();
for (const pkg of packages) {
for (const [specifier, target] of pkg.exportTargets) targets.set(specifier, target);
}
return targets;
}
/** The real-tree R11 run used by check.ts. */
export function checkPackageBoundaries(repoRoot: string): PackageBoundaryViolation[] {
const packages = readWorkspacePackages(repoRoot);
if (packages.length === 0) return [];
const rootDependencies = rootWorkspaceDependencyNames(repoRoot);
const violations: PackageBoundaryViolation[] = [];
for (const pkg of packages) {
for (const file of walkTsFiles(repoRoot, pkg.dir)) {
const source = fs.readFileSync(path.join(repoRoot, file), 'utf8');
violations.push(
...checkPackageInternalSites(
pkg,
specifierSites(file, source),
packages,
insideCompiledSources(file),
),
);
}
}
for (const root of ['src', 'test', 'scripts']) {
for (const file of walkTsFiles(repoRoot, root)) {
// Gate tests under scripts/ carry import syntax inside fixture strings
// (which is why this reads module records instead of scanning lines);
// src/ and test/ suites stay covered — they import packages for real.
if (root === 'scripts' && file.endsWith('.test.ts')) continue;
const source = fs.readFileSync(path.join(repoRoot, file), 'utf8');
violations.push(
...checkRootSites(
specifierSites(file, source),
packages,
rootDependencies,
insideCompiledSources(file),
),
);
}
}
return violations;
}
/** Success-line fragment for check.ts's report. */
export function packageBoundariesSummary(repoRoot: string): string {
const packages = readWorkspacePackages(repoRoot);
const exported = packages.reduce((sum, pkg) => sum + pkg.exportTargets.size, 0);
return (
`R11 holds ${packages.length} workspace package(s) behind ${exported} exported subpath(s) ` +
`with zero undeclared or relative-tunnel import routes (the compiler owns specifier ` +
`resolution for compiled sources)`
);
}