Repository navigation
Expand file tree
/
Copy pathverify-package-dependencies.ts
More file actions
1106 lines (1050 loc) · 49.4 KB
/
Copy pathverify-package-dependencies.ts
File metadata and controls
1106 lines (1050 loc) · 49.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Verify and repair npm dependency sections from published Client and Host faces, and keep root-provided type
* packages out of workspace manifests.
*/
import { spawnSync } from 'node:child_process'
import { existsSync, globSync, readFileSync, writeFileSync } from 'node:fs'
import { availableParallelism } from 'node:os'
import { dirname, extname, join, normalize, relative, resolve, sep } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Worker } from 'node:worker_threads'
import ts from 'typescript'
import { WorkspaceTypertGenerator } from '../packages/typert/generator/src/workspace.ts'
import { PACKAGE_ASSET_EXPORT } from '../packages/client/modules/src/assets.ts'
import { writeModuleGraph } from './gen-module-graph.ts'
import {
hasClientDeclaration,
PACKAGE_DEPENDENCY_POLICY,
type PackageDependencyPolicy,
} from './package-dependency-policy.ts'
import type {
SourceUsesWorkerRequest,
SourceUsesWorkerResult,
} from './package-source-uses.worker.ts'
import {
ROOT_TYPE_PACKAGES,
addUse,
normalizePath,
collectRuntimeLocalSourceSpecifiers,
declaredSections,
mutableSection,
packageNameOf,
readAllSourceUses,
section,
type DependencySection,
} from './source-parse-uses.ts'
const GATE = 'verify-package-dependencies'
const CORDIS = '@deepseek-ai/cordis'
/**
* Type packages declared only in the root devDependencies. Each package-local pnpm link is one more
* location that TypeScript scans when it computes module specifiers for every JSX file.
*/
function workspaceRange(name: string): 'workspace:*' | 'workspace:~' {
return name === '@deepseek-ai/dsh' || name.startsWith('@deepseek-ai/dsh-') ? 'workspace:*' : 'workspace:~'
}
const RELEASE_MANIFEST_GLOB = 'packages/!(experimental)/*/package.json'
/** Every package group, experimental included, follows the same published dependency policy. */
const POLICY_MANIFEST_GLOB = 'packages/*/*/package.json'
const WORKSPACE_MANIFEST_GLOBS = [
'apps/*/package.json',
'packages/*/*/package.json',
'vendor/*/package.json',
]
export type PackageDependencyRole = 'client-only' | 'client-host' | 'configured-host'
/** One workspace package the dependency policy covers, with its resolved role. */
export type SelectedWorkspacePackage = WorkspacePackageManifest & { readonly role: PackageDependencyRole }
/** Upper bound on source-walk workers: each one pays its own TypeScript module load. */
export const MAX_DEPENDENCY_WORKERS = 16
/** Manifest fields read and repaired by the package dependency policy. */
export interface PackageDependencyManifest {
name?: string
version?: string
exports?: unknown
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
optionalDependencies?: Record<string, string>
peerDependencies?: Record<string, string>
peerDependenciesMeta?: Record<string, unknown>
dsh?: { client?: { inject?: string[] } }
}
/** One workspace package and its source location. */
export interface WorkspacePackageManifest {
readonly dir: string
readonly manifestPath: string
readonly manifest: PackageDependencyManifest
readonly name: string
}
/** Source and manifest facts for one package covered by the policy. */
export interface PackageDependencyFacts {
readonly manifestPath: string
readonly role: PackageDependencyRole
readonly manifest: PackageDependencyManifest
readonly workspaceNames: ReadonlySet<string>
readonly allSourceUses: ReadonlyMap<string, readonly string[]>
readonly hostRuntimeSourceUses: ReadonlyMap<string, readonly string[]>
readonly hostRuntimeExportUses: readonly HostRuntimeExportUse[]
readonly peerRequiredHostDependencies: ReadonlySet<string>
readonly configurationOnlyDevDependencies: ReadonlySet<string>
readonly clientInject: ReadonlySet<string>
}
/** One runtime export used by an authored or generated Host module. */
export interface HostRuntimeExportUse {
readonly packageName: string
readonly specifier: string
readonly exportName: string
readonly sourcePath: string
readonly line: number
readonly column: number
readonly sourceLine: string
}
/** Complete policy input read from the repository. */
export interface PackageDependencyState {
readonly facts: readonly PackageDependencyFacts[]
readonly packages: readonly WorkspacePackageManifest[]
readonly policyViolations: readonly string[]
readonly workspaceNames: ReadonlySet<string>
}
export interface ExpectedPackageDependency {
readonly section: 'dependencies' | 'devDependencies' | 'peer-dev'
readonly origins: readonly string[]
}
export function readWorkspacePackageManifests(root: string): {
all: WorkspacePackageManifest[]
release: WorkspacePackageManifest[]
policy: WorkspacePackageManifest[]
} {
const read = (manifestPath: string): WorkspacePackageManifest => {
const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) as PackageDependencyManifest
if (typeof manifest.name !== 'string') throw new Error(`${manifestPath}: missing package name`)
return {
dir: dirname(manifestPath),
manifestPath,
manifest,
name: manifest.name,
}
}
const all = globSync(WORKSPACE_MANIFEST_GLOBS, { cwd: root }).map(normalizePath).sort().map(read)
const subset = (pattern: string): WorkspacePackageManifest[] => {
const paths = new Set(globSync(pattern, { cwd: root }).map(normalizePath))
return all.filter(pkg => paths.has(pkg.manifestPath))
}
return { all, release: subset(RELEASE_MANIFEST_GLOB), policy: subset(POLICY_MANIFEST_GLOB) }
}
function duplicates(values: readonly string[]): string[] {
const seen = new Set<string>()
const duplicated = new Set<string>()
for (const value of values) {
if (seen.has(value)) duplicated.add(value)
seen.add(value)
}
return [...duplicated].sort()
}
/** Discover Client faces and configured Host packages, validating explicit overrides. */
export function discoverPackageDependencyScope(
packages: readonly WorkspacePackageManifest[],
policy: PackageDependencyPolicy,
): { selected: Array<WorkspacePackageManifest & { role: PackageDependencyRole }>; violations: string[] } {
const violations: string[] = []
const byName = new Map(packages.map(pkg => [pkg.name, pkg]))
const include = new Set(policy.clientFaceInclude)
const exclude = new Set(policy.clientFaceExclude)
const host = new Set(policy.hostPackages)
for (const [field, values] of [
['clientFaceInclude', policy.clientFaceInclude],
['clientFaceExclude', policy.clientFaceExclude],
['hostPackages', policy.hostPackages],
] as const) {
for (const name of duplicates(values)) violations.push(`${field} lists ${name} more than once`)
for (const name of values) {
if (!byName.has(name)) violations.push(`${field} names unknown package ${name}`)
}
}
for (const name of include) {
if (exclude.has(name)) violations.push(`${name} appears in both clientFaceInclude and clientFaceExclude`)
const pkg = byName.get(name)
if (pkg !== undefined
&& (pkg.manifestPath.startsWith('packages/client/') || hasClientDeclaration(pkg.manifest.dsh))) {
violations.push(`clientFaceInclude redundantly names automatically discovered package ${name}`)
}
}
for (const name of exclude) {
const pkg = byName.get(name)
if (pkg !== undefined && pkg.manifestPath.startsWith('packages/client/')) {
violations.push(`clientFaceExclude cannot exempt packages/client package ${name}`)
} else if (pkg !== undefined && !hasClientDeclaration(pkg.manifest.dsh)) {
violations.push(`clientFaceExclude names ${name}, which declares no dsh.client entry`)
}
}
const selected: Array<WorkspacePackageManifest & { role: PackageDependencyRole }> = []
for (const pkg of packages) {
const clientDirectory = pkg.manifestPath.startsWith('packages/client/')
const clientHost = (hasClientDeclaration(pkg.manifest.dsh) || include.has(pkg.name)) && !exclude.has(pkg.name)
const clientOnly = clientDirectory && !clientHost
const configuredHost = host.has(pkg.name)
if (configuredHost && (clientHost || clientOnly)) {
violations.push(`hostPackages redundantly names Client-faced package ${pkg.name}`)
}
const role = clientHost ? 'client-host' : clientOnly ? 'client-only' : configuredHost ? 'configured-host' : undefined
if (role !== undefined) selected.push({ ...pkg, role })
}
return {
selected: selected.sort((left, right) => left.manifestPath.localeCompare(right.manifestPath)),
violations: [...new Set(violations)].sort(),
}
}
const NAMESPACE_RUNTIME_EXPORT = '*'
const SIDE_EFFECT_RUNTIME_EXPORT = '(side effect)'
interface RuntimeSourceExportUse {
readonly specifier: string
readonly exportName: string
readonly line: number
readonly column: number
readonly sourceLine: string
}
/** Collect exact runtime exports imported or re-exported by one source file. */
export function collectRuntimeSourceExportUses(path: string, source: string): RuntimeSourceExportUse[] {
const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
const uses = new Map<string, RuntimeSourceExportUse>()
const sourceLines = source.split(/\r?\n/u)
const lazyRequireBindings = new Set<string>()
const lazyRequireNamespaces = new Set<string>()
for (const statement of sourceFile.statements) {
if (!ts.isImportDeclaration(statement)
|| !ts.isStringLiteralLike(statement.moduleSpecifier)
|| statement.moduleSpecifier.text !== '@deepseek-ai/dsh-lazy-require') continue
const bindings = statement.importClause?.namedBindings
if (bindings !== undefined && ts.isNamespaceImport(bindings)) {
lazyRequireNamespaces.add(bindings.name.text)
} else if (bindings !== undefined) {
for (const element of bindings.elements) {
if ((element.propertyName ?? element.name).text === 'createLazyRequire') {
lazyRequireBindings.add(element.name.text)
}
}
}
}
const record = (specifier: string, exportName: string, locationNode: ts.Node): void => {
const key = `${specifier}\0${exportName}`
if (uses.has(key)) return
const position = sourceFile.getLineAndCharacterOfPosition(locationNode.getStart(sourceFile))
uses.set(key, {
specifier,
exportName,
line: position.line + 1,
column: position.character + 1,
sourceLine: sourceLines[position.line]?.trim() ?? '',
})
}
const add = (
specifierNode: ts.Expression | undefined,
exportName: string,
locationNode: ts.Node = specifierNode ?? sourceFile,
): void => {
if (specifierNode === undefined || !ts.isStringLiteralLike(specifierNode)) return
if (packageNameOf(specifierNode.text) === undefined) return
record(specifierNode.text, exportName, locationNode)
}
const visit = (node: ts.Node): void => {
if (ts.isImportDeclaration(node)) {
const clause = node.importClause
if (clause === undefined) {
add(node.moduleSpecifier, SIDE_EFFECT_RUNTIME_EXPORT)
} else if (clause.phaseModifier !== ts.SyntaxKind.TypeKeyword) {
if (clause.name !== undefined) add(node.moduleSpecifier, 'default', clause.name)
const bindings = clause.namedBindings
if (bindings !== undefined && ts.isNamespaceImport(bindings)) {
add(node.moduleSpecifier, NAMESPACE_RUNTIME_EXPORT, bindings.name)
} else if (bindings !== undefined && bindings.elements.length === 0) {
add(node.moduleSpecifier, SIDE_EFFECT_RUNTIME_EXPORT)
} else if (bindings !== undefined) {
for (const element of bindings.elements) {
const imported = element.propertyName ?? element.name
if (!element.isTypeOnly) add(node.moduleSpecifier, imported.text, imported)
}
}
}
} else if (ts.isExportDeclaration(node) && !node.isTypeOnly) {
const clause = node.exportClause
if (clause === undefined || ts.isNamespaceExport(clause)) {
add(node.moduleSpecifier, NAMESPACE_RUNTIME_EXPORT)
} else if (clause.elements.length === 0) {
add(node.moduleSpecifier, SIDE_EFFECT_RUNTIME_EXPORT)
} else {
for (const element of clause.elements) {
const imported = element.propertyName ?? element.name
if (!element.isTypeOnly) add(node.moduleSpecifier, imported.text, imported)
}
}
} else if (ts.isImportEqualsDeclaration(node)
&& !node.isTypeOnly
&& ts.isExternalModuleReference(node.moduleReference)) {
add(node.moduleReference.expression, NAMESPACE_RUNTIME_EXPORT, node.name)
} else if (ts.isCallExpression(node)) {
const lazyRequire = ts.isIdentifier(node.expression)
? lazyRequireBindings.has(node.expression.text)
: ts.isPropertyAccessExpression(node.expression)
&& ts.isIdentifier(node.expression.expression)
&& lazyRequireNamespaces.has(node.expression.expression.text)
&& node.expression.name.text === 'createLazyRequire'
if (node.expression.kind === ts.SyntaxKind.ImportKeyword
|| ts.isIdentifier(node.expression) && node.expression.text === 'require'
|| lazyRequire) add(node.arguments[0], NAMESPACE_RUNTIME_EXPORT)
} else if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)) {
record('react/jsx-runtime', NAMESPACE_RUNTIME_EXPORT, node)
}
ts.forEachChild(node, visit)
}
visit(sourceFile)
return [...uses.values()].sort((left, right) =>
left.specifier.localeCompare(right.specifier)
|| left.exportName.localeCompare(right.exportName)
|| left.line - right.line
|| left.column - right.column)
}
function resolveLocal(importer: string, specifier: string): string | undefined {
const raw = resolve(dirname(importer), specifier)
const candidates = extname(raw) === ''
? [`${raw}.ts`, `${raw}.tsx`, `${raw}.mts`, `${raw}.cts`, join(raw, 'index.ts'), join(raw, 'index.tsx')]
: [raw, raw.replace(/\.js$/, '.ts'), raw.replace(/\.jsx?$/, '.tsx'), raw.replace(/\.mjs$/, '.mts'), raw.replace(/\.cjs$/, '.cts')]
return candidates.find(candidate => existsSync(candidate))
}
function nodeExportTargets(value: unknown): string[] {
if (typeof value === 'string') return /\.[cm]?js$/.test(value) ? [value] : []
if (Array.isArray(value)) return value.flatMap(nodeExportTargets)
if (value === null || typeof value !== 'object') return []
return Object.entries(value)
.filter(([condition]) => ['node', 'import', 'require', 'default'].includes(condition))
.flatMap(([, target]) => nodeExportTargets(target))
}
function hasGeneratedHostExport(pkg: WorkspacePackageManifest): boolean {
const exports = pkg.manifest.exports
return exports !== null && typeof exports === 'object'
&& nodeExportTargets((exports as Record<string, unknown>)['./typert']).includes('./lib/typert.host.js')
}
/** Generate Host modules in memory, without the build plugin's artifact writes. */
function generatedHostSources(root: string, packages: readonly WorkspacePackageManifest[]): ReadonlyMap<string, string> {
const selected = packages.filter(hasGeneratedHostExport)
if (selected.length === 0) return new Map()
const artifacts = new WorkspaceTypertGenerator(root).generate(selected.map(pkg => pkg.name), ['host'])
const sources = new Map(artifacts.map(artifact => [artifact.package, artifact.js]))
for (const pkg of selected) {
if (!sources.has(pkg.name)) throw new Error(`${pkg.manifestPath}: declared Host Typert export has no generated module`)
}
return sources
}
/**
* Source-backed Node exports. Generated Typert artifacts have no standalone source entry; `./client`, `./src`, and
* package-asset subpaths publish no Host code.
*/
function hostSourceEntries(root: string, pkg: WorkspacePackageManifest): string[] {
const entry = resolve(root, pkg.dir, 'src/index.ts')
if (!existsSync(entry)) {
throw new Error(`${pkg.manifestPath}: Host runtime entry ${normalizePath(relative(root, entry))} does not exist`)
}
const entries = new Set([entry])
const exports = pkg.manifest.exports
if (exports === null || typeof exports !== 'object') return [...entries]
for (const [subpath, declaration] of Object.entries(exports as Record<string, unknown>)) {
if (subpath === '.' || subpath === './package.json' || subpath === PACKAGE_ASSET_EXPORT
|| /^\.\/(?:client|src)(?:\/|$)/.test(subpath)) continue
const types = declaration !== null && typeof declaration === 'object' && 'types' in declaration
? declaration.types
: undefined
for (const runtime of nodeExportTargets(declaration)) {
const generatedFace = subpath === './typert' ? 'host' : subpath === './remote' ? 'remote-client' : undefined
if (generatedFace !== undefined
&& runtime === `./lib/typert.${generatedFace}.js`
&& types === `./lib/typert.${generatedFace}.d.ts`) continue
const target = typeof types === 'string' && types.startsWith('./lib/types/') ? types : runtime
if (!target.startsWith('./lib/')) {
throw new Error(`${pkg.manifestPath}: Host export ${subpath} cannot map ${target} to a source entry`)
}
const source = target.replace(/^\.\/lib\/(?:types\/)?/, './src/').replace(/\.d\.([cm]?)ts$/, '.$1js')
const matched = source.includes('*')
? globSync(source.replace(/\.[cm]?js$/, '.{ts,tsx,mts,cts}'), { cwd: resolve(root, pkg.dir) })
.map(path => resolve(root, pkg.dir, path))
: [resolveLocal(resolve(root, pkg.manifestPath), source)].filter(path => path !== undefined)
if (matched.length === 0) {
throw new Error(`${pkg.manifestPath}: Host export ${subpath} has no source entry for ${target}`)
}
for (const path of matched) entries.add(path)
}
}
return [...entries].sort()
}
/** tsdown build faces the repository build runs; each package config contributes its configs under both. */
const BUILD_FACES = ['host', 'client'] as const
/** One tsdown configuration as far as Host entry discovery reads it. */
interface BuildEntryConfig {
readonly entry?: unknown
readonly platform?: unknown
}
/** Flatten a tsdown entry declaration to its paths: a string, a list, or an output-name map. */
function buildEntryPaths(entry: unknown, configPath: string): string[] {
if (entry === undefined || entry === '') return []
if (typeof entry === 'string') return [entry]
if (Array.isArray(entry) && entry.every(value => typeof value === 'string')) return entry
if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)
&& Object.values(entry).every(value => typeof value === 'string')) return Object.values(entry) as string[]
throw new Error(`${configPath}: tsdown entry ${JSON.stringify(entry)} is not a path, a path list, or an output-name map`)
}
/**
* Read the Host-side source entries a package-local `tsdown.config.ts` builds, such as Worker-thread and child-process
* entries that no package export names. The config is evaluated under every repository build face; configs for the
* browser platform and entries under `src/client/` (Client faces, including the Node Client half) are not Host
* entries. A package without a local config builds only the workspace default `index` and `startup` entries, which
* its `src/index.ts` and exports already cover.
* @param root - Repository containing the package.
* @param pkg - Package whose build configuration is read.
* @returns Absolute source paths, sorted; empty without a package-local config.
* @throws {Error} when the config has no usable default export or an entry has no source module.
*/
export async function readHostBuildEntries(root: string, pkg: WorkspacePackageManifest): Promise<string[]> {
const configPath = resolve(root, pkg.dir, 'tsdown.config.ts')
if (!existsSync(configPath)) return []
const display = normalizePath(relative(root, configPath))
const loaded = await import(pathToFileURL(configPath).href) as { default?: unknown }
const exported = loaded.default
if (exported === undefined || exported === null) throw new Error(`${display}: tsdown config has no default export`)
const configs: BuildEntryConfig[] = []
for (const face of BUILD_FACES) {
const value: unknown = typeof exported === 'function'
? await (exported as (inline: { env: Record<string, string> }) => unknown)({ env: { DSH_BUILD_FACE: face } })
: exported
configs.push(...(Array.isArray(value) ? value : [value]) as BuildEntryConfig[])
}
const packageDir = resolve(root, pkg.dir)
const clientDir = join(packageDir, 'src', 'client') + sep
const entries = new Set<string>()
for (const config of configs) {
if (config.platform === 'browser') continue
for (const path of buildEntryPaths(config.entry, display)) {
if (!/^(?:\.\/)?(?:lib\/types|src)\//.test(path)) {
throw new Error(`${display}: tsdown entry ${path} cannot map to a source entry`)
}
const source = path.replace(/^(?:\.\/)?(?:lib\/types|src)\//, './src/')
const matched = /[*{]/.test(source)
? globSync(source.replace(/\.[cm]?[jt]sx?$/, '.{ts,tsx,mts,cts}'), { cwd: packageDir }).map(match => resolve(packageDir, match))
: [resolveLocal(resolve(root, pkg.manifestPath), source)].filter(match => match !== undefined)
if (matched.length === 0 && !/[*{]/.test(source)) {
throw new Error(`${display}: tsdown entry ${path} has no source module`)
}
for (const match of matched) if (!match.startsWith(clientDir)) entries.add(match)
}
}
return [...entries].sort()
}
function readHostRuntimeUses(
root: string,
pkg: WorkspacePackageManifest,
hostBuildEntries: readonly string[],
generatedHostSource?: string,
): {
packageUses: Map<string, string[]>
exportUses: HostRuntimeExportUse[]
} {
const packageUses = new Map<string, string[]>()
const exportUses = new Map<string, HostRuntimeExportUse>()
const seen = new Set<string>()
const collect = (displayPath: string, source: string): void => {
for (const use of collectRuntimeSourceExportUses(displayPath, source)) {
const name = packageNameOf(use.specifier)
if (name === undefined) continue
addUse(packageUses, name, displayPath)
const fact = { packageName: name, ...use, sourcePath: displayPath }
exportUses.set(`${use.specifier}\0${use.exportName}\0${displayPath}\0${String(use.line)}\0${String(use.column)}`, fact)
}
}
const visit = (path: string): void => {
const normalized = normalize(path)
if (seen.has(normalized)) return
seen.add(normalized)
const source = readFileSync(normalized, 'utf8')
const displayPath = normalizePath(relative(root, normalized))
collect(displayPath, source)
for (const specifier of collectRuntimeLocalSourceSpecifiers(normalized, source)) {
const target = resolveLocal(normalized, specifier)
if (target !== undefined) visit(target)
}
}
for (const entry of [...hostSourceEntries(root, pkg), ...hostBuildEntries]) visit(entry)
const generated = generatedHostSource ?? generatedHostSources(root, [pkg]).get(pkg.name)
if (generated !== undefined) collect(`${normalizePath(pkg.dir)}/lib/typert.host.js`, generated)
return {
packageUses,
exportUses: [...exportUses.values()].sort((left, right) =>
left.packageName.localeCompare(right.packageName)
|| left.specifier.localeCompare(right.specifier)
|| left.exportName.localeCompare(right.exportName)
|| left.sourcePath.localeCompare(right.sourcePath)
|| left.line - right.line
|| left.column - right.column),
}
}
/**
* Read authored and generated source usage for one already-classified package.
* @param root - Repository containing source files and face tsconfigs.
* @param pkg - Package manifest and directory.
* @param role - Selected dependency policy role.
* @param workspaceNames - Workspace package identities.
* @param policy - Reviewed Host exports, required services, and development-only relationships.
* @param generatedHostSource - Host module already emitted in memory by a batched Typert pass.
* @returns Source-derived dependency facts without writing build artifacts; Host roles include the build entries
* {@link readHostBuildEntries} reads from the package's tsdown config.
*/
export async function readPackageDependencyFacts(
root: string,
pkg: WorkspacePackageManifest,
role: PackageDependencyRole,
workspaceNames: ReadonlySet<string>,
policy: PackageDependencyPolicy = PACKAGE_DEPENDENCY_POLICY,
generatedHostSource?: string,
precomputedSourceUses?: Map<string, string[]>,
): Promise<PackageDependencyFacts> {
const inject = pkg.manifest.dsh?.client?.inject ?? []
const hostRuntime = role === 'client-only'
? { packageUses: new Map<string, string[]>(), exportUses: [] }
: readHostRuntimeUses(root, pkg, await readHostBuildEntries(root, pkg), generatedHostSource)
const servicePeers = policy.requiredServicePeers?.[pkg.name] ?? []
const allSourceUses = precomputedSourceUses ?? readAllSourceUses(root, pkg)
for (const name of servicePeers) {
if (!workspaceNames.has(name) || !allSourceUses.has(name)) {
throw new Error(`${pkg.manifestPath}: requiredServicePeers must name a referenced workspace package: ${name}`)
}
}
return {
manifestPath: pkg.manifestPath,
role,
manifest: pkg.manifest,
workspaceNames,
allSourceUses,
hostRuntimeSourceUses: hostRuntime.packageUses,
hostRuntimeExportUses: hostRuntime.exportUses,
peerRequiredHostDependencies: new Set([
...hostRuntime.exportUses
.filter(use => policy.peerRequiredHostExports[use.specifier]?.includes(use.exportName) === true)
.map(use => use.packageName),
...servicePeers,
]),
configurationOnlyDevDependencies: new Set(
policy.configurationOnlyDevDependencies[pkg.manifest.name ?? ''] ?? [],
),
clientInject: new Set(inject.map(packageNameOf).filter(name => name !== undefined)),
}
}
/** Validate reviewed Host export classifications against current source facts. */
export function collectHostDependencyExportPolicyViolations(
facts: readonly PackageDependencyFacts[],
workspaceNames: ReadonlySet<string>,
policy: Pick<PackageDependencyPolicy, 'duplicateSafePackages' | 'peerRequiredHostExports' | 'safeHostDependencyExports'>,
): string[] {
const violations: string[] = []
const allRuntimeUses = facts.flatMap(fact => fact.hostRuntimeExportUses)
const duplicateSafePackages = new Set(policy.duplicateSafePackages ?? [])
for (const packageName of duplicates(policy.duplicateSafePackages ?? [])) {
violations.push(`duplicateSafePackages lists ${packageName} more than once`)
}
for (const packageName of duplicateSafePackages) {
if (!workspaceNames.has(packageName)) {
violations.push(`duplicateSafePackages names unknown workspace package ${packageName}`)
}
}
const classifications = [
['safeHostDependencyExports', policy.safeHostDependencyExports],
['peerRequiredHostExports', policy.peerRequiredHostExports],
] as const
for (const [field, entries] of classifications) {
for (const [specifier, exportNames] of Object.entries(entries)) {
const provider = packageNameOf(specifier)
if (provider === undefined || !workspaceNames.has(provider)) {
violations.push(`${field} specifier ${specifier} is not a workspace package`)
} else if (duplicateSafePackages.has(provider)) {
violations.push(`${field} redundantly classifies duplicate-install-safe package ${specifier}`)
}
if (exportNames.length === 0) {
violations.push(`${field} lists no exports for ${specifier}`)
}
for (const exportName of duplicates(exportNames)) {
violations.push(`${field} lists ${specifier} export ${exportName} more than once`)
}
for (const exportName of exportNames) {
if (exportName === '' || exportName === NAMESPACE_RUNTIME_EXPORT || exportName === SIDE_EFFECT_RUNTIME_EXPORT) {
violations.push(`${field} cannot classify unbounded ${specifier} export ${exportName}`)
continue
}
if (!allRuntimeUses.some(use => use.specifier === specifier && use.exportName === exportName)) {
violations.push(`${field} lists unused ${specifier} export ${exportName}`)
}
if (field === 'safeHostDependencyExports'
&& policy.peerRequiredHostExports[specifier]?.includes(exportName) === true) {
violations.push(`${specifier} export ${exportName} appears in both Host export classifications`)
}
}
}
}
for (const fact of facts) {
for (const use of fact.hostRuntimeExportUses) {
if (use.packageName === fact.manifest.name || use.packageName === CORDIS) continue
if (!workspaceNames.has(use.packageName)) continue
if (duplicateSafePackages.has(use.packageName)) continue
if (policy.safeHostDependencyExports[use.specifier]?.includes(use.exportName) === true) continue
if (policy.peerRequiredHostExports[use.specifier]?.includes(use.exportName) === true) continue
violations.push(
`${use.sourcePath}:${String(use.line)}:${String(use.column)}: `
+ `${use.specifier}#${use.exportName} is not classified as safe or peer-required — ${use.sourceLine}`,
)
}
}
return violations.sort()
}
/**
* Read every package covered by the current dependency policy.
* @param root - Repository containing the workspace manifests, sources, and package build configs.
* @param policy - Reviewed scope overrides and Host export classifications.
* @returns Facts for every covered package, the covered manifests, and policy configuration violations.
*/
export async function readPackageDependencyState(
root: string,
policy: PackageDependencyPolicy = PACKAGE_DEPENDENCY_POLICY,
): Promise<PackageDependencyState> {
const packages = readWorkspacePackageManifests(root)
const workspaceNames = new Set(packages.all.map(pkg => pkg.name))
const discovered = discoverPackageDependencyScope(packages.policy, policy)
const generated = generatedHostSources(root, discovered.selected.filter(pkg => pkg.role !== 'client-only'))
const facts = await readPackageDependencyFactsConcurrently(root, discovered.selected, workspaceNames, policy, generated)
const selectedNames = new Set(facts.map(fact => fact.manifest.name))
return {
facts,
packages: packages.policy,
policyViolations: [
...discovered.violations,
...collectHostDependencyExportPolicyViolations(facts, workspaceNames, policy),
...(['configurationOnlyDevDependencies', 'requiredServicePeers'] as const).flatMap(field =>
Object.keys(policy[field] ?? {})
.filter(name => !selectedNames.has(name))
.map(name => `${field} names unmanaged package ${name}`)),
].sort(),
workspaceNames,
}
}
/**
* Read dependency facts for every selected package, walking package sources in parallel.
*
* Walking a package's `src` tree with the TypeScript parser is the expensive part of
* this gate and shares no state across packages, so those walks run in worker threads
* while the caller's package order is preserved for the policy checks.
* @param root - Repository containing the workspace sources and build configs.
* @param packages - Selected packages, in policy order.
* @param workspaceNames - Identities of every workspace package.
* @param policy - Reviewed scope overrides and Host export classifications.
* @param generated - Host modules the batched Typert pass emitted in memory, keyed by package name.
* @param workers - Worker count for the source walk; defaults to the host CPU count, capped at {@link MAX_DEPENDENCY_WORKERS}.
* @returns Facts in the same order as `packages`.
*/
export async function readPackageDependencyFactsConcurrently(
root: string,
packages: readonly SelectedWorkspacePackage[],
workspaceNames: ReadonlySet<string>,
policy: PackageDependencyPolicy,
generated: ReadonlyMap<string, string>,
workers = Math.min(availableParallelism(), packages.length, MAX_DEPENDENCY_WORKERS),
): Promise<PackageDependencyFacts[]> {
const sourceUses = await readSourceUses(root, packages, workers)
const facts: PackageDependencyFacts[] = []
for (const pkg of packages) {
facts.push(await readPackageDependencyFacts(
root,
pkg,
pkg.role,
workspaceNames,
policy,
generated.get(pkg.name),
sourceUses.get(pkg.dir),
))
}
return facts
}
/** Source uses per package directory, collected either in-process or by worker threads. */
async function readSourceUses(
root: string,
packages: readonly SelectedWorkspacePackage[],
workers: number,
): Promise<Map<string, Map<string, string[]>>> {
if (workers < 2 || packages.length < 2) {
return new Map(packages.map(pkg => [pkg.dir, readAllSourceUses(root, pkg)]))
}
const sizes = sliceSizes(packages.length, workers)
const tasks = packages.map((pkg, index) => ({ index, dir: pkg.dir, name: pkg.name, manifest: pkg.manifest }))
const slices: typeof tasks[] = []
let offset = 0
for (const size of sizes) {
slices.push(tasks.slice(offset, offset + size))
offset += size
}
const collected = (await Promise.all(slices.map(async slice => runSourceUsesWorker(root, slice)))).flat()
const byName = new Map(collected.map(result => [result.name, result.uses]))
return new Map(packages.map(pkg => [pkg.dir, byName.get(pkg.name) ?? new Map<string, string[]>()]))
}
/**
* Run one slice of packages in a worker thread.
* @param root - Repository containing the workspace sources.
* @param tasks - Packages this worker walks.
* @returns one result per task.
* @throws If the worker crashes or exits before reporting.
*/
function runSourceUsesWorker(root: string, tasks: readonly SourceUsesTaskForWorker[]): Promise<SourceUsesWorkerResult[]> {
const request: SourceUsesWorkerRequest = { root, tasks }
const url = new URL('./package-source-uses.worker.ts', import.meta.url)
return new Promise((resolveResults, rejectResults) => {
const worker = new Worker(url, { workerData: request })
let settled = false
worker.once('message', (results: SourceUsesWorkerResult[]) => {
settled = true
void worker.terminate()
resolveResults(results)
})
worker.once('error', (error) => {
if (settled) return
settled = true
rejectResults(error)
})
worker.once('exit', (code) => {
if (settled) return
settled = true
rejectResults(new Error(`${GATE}: source-uses worker exited with ${String(code)} before reporting`))
})
})
}
interface SourceUsesTaskForWorker {
readonly index: number
readonly dir: string
readonly name: string
readonly manifest: PackageDependencyManifest
}
/**
* Distribute a task count over a worker count as evenly as possible.
* @param tasks - Number of tasks to place.
* @param workers - Number of workers that must stay busy.
* @returns One slice size per non-empty slice.
*/
export function sliceSizes(tasks: number, workers: number): number[] {
const slices = Math.min(tasks, Math.max(1, workers))
const base = Math.floor(tasks / slices)
const remainder = tasks % slices
return Array.from({ length: slices }, (_, index) => base + (index < remainder ? 1 : 0))
}
/** Derive the required npm section for each relationship owned by the policy. */
export function expectedPackageDependencies(
facts: PackageDependencyFacts,
): ReadonlyMap<string, ExpectedPackageDependency> {
const expected = new Map<string, { section: ExpectedPackageDependency['section']; origins: Set<string> }>()
const add = (name: string, sectionName: ExpectedPackageDependency['section'], origin: string): void => {
if (name === facts.manifest.name || name === CORDIS) return
const current = expected.get(name)
const section = current?.section === 'peer-dev' || sectionName === 'peer-dev'
? 'peer-dev'
: current?.section === 'dependencies' || sectionName === 'dependencies'
? 'dependencies'
: 'devDependencies'
expected.set(name, { section, origins: new Set([...(current?.origins ?? []), origin]) })
}
expected.set(CORDIS, { section: 'peer-dev', origins: new Set(['shared Cordis runtime']) })
for (const [name, paths] of facts.allSourceUses) {
for (const path of paths) add(name, 'devDependencies', path)
}
if (facts.role !== 'configured-host') {
for (const sectionName of ['dependencies', 'optionalDependencies'] as const) {
for (const name of Object.keys(facts.manifest[sectionName] ?? {})) {
if (!facts.workspaceNames.has(name)) add(name, 'devDependencies', 'declared browser build input')
}
}
}
for (const name of facts.clientInject) {
if (facts.workspaceNames.has(name)) add(name, 'devDependencies', 'dsh.client.inject')
}
for (const name of facts.configurationOnlyDevDependencies) {
if (facts.workspaceNames.has(name)) add(name, 'devDependencies', 'configured development-only relationship')
}
for (const name of Object.keys(facts.manifest.peerDependencies ?? {})) {
if (name !== CORDIS) add(name, 'devDependencies', 'existing non-Cordis peer')
}
for (const [name, paths] of facts.hostRuntimeSourceUses) {
const expectedSection = facts.workspaceNames.has(name) && facts.peerRequiredHostDependencies.has(name)
? 'peer-dev'
: 'dependencies'
for (const path of paths) add(name, expectedSection, path)
}
for (const name of facts.peerRequiredHostDependencies) {
if (!facts.hostRuntimeSourceUses.has(name)) add(name, 'peer-dev', 'required Cordis service')
}
return new Map([...expected].map(([name, rule]) => [name, {
section: rule.section,
origins: [...rule.origins].sort(),
}]))
}
interface ManagedRuntimeEdge {
readonly consumer: string
readonly dependency: string
readonly exports: readonly string[]
}
function managedRuntimeEdges(
state: PackageDependencyState,
expectedSection: 'dependencies' | 'peer-dev',
): ManagedRuntimeEdge[] {
return state.facts.flatMap(facts => [...expectedPackageDependencies(facts)]
.filter(([name, rule]) => name !== CORDIS && rule.section === expectedSection)
.map(([dependency]) => ({
consumer: facts.manifest.name ?? facts.manifestPath,
dependency,
exports: [...new Set(facts.hostRuntimeExportUses
.filter(use => use.packageName === dependency)
.map(use => `${use.specifier}#${use.exportName}`))].sort(),
})))
.sort((left, right) =>
left.consumer.localeCompare(right.consumer) || left.dependency.localeCompare(right.dependency))
}
/** Format Host runtime edges whose reviewed exports permit ordinary dependencies. */
export function formatManagedRuntimeDependencies(state: PackageDependencyState): string[] {
const rows = managedRuntimeEdges(state, 'dependencies')
const packages = new Set(rows.map(row => row.consumer)).size
return [
`${GATE}: ${String(rows.length)} managed Host runtime edge(s) remain in dependencies across ${String(packages)} package(s):`,
...rows.map(row => ` ${row.consumer} -> ${row.dependency}: ${row.exports.join(', ')}`),
]
}
/** Format Host runtime edges retained as peers for shared exports or required services. */
export function formatPeerRequiredRuntimeDependencies(state: PackageDependencyState): string[] {
const rows = managedRuntimeEdges(state, 'peer-dev')
const packages = new Set(rows.map(row => row.consumer)).size
return [
`${GATE}: ${String(rows.length)} Host runtime edge(s) remain in peerDependencies for shared exports or required services across ${String(packages)} package(s):`,
...rows.map(row => ` ${row.consumer} -> ${row.dependency}: ${row.exports.join(', ') || 'required Cordis service'}`),
]
}
function describeSections(sections: readonly DependencySection[]): string {
return sections.length === 0 ? 'no dependency section' : sections.join(' + ')
}
/** Return all manifest and policy violations in stable order. */
export function collectPackageDependencyViolations(state: PackageDependencyState): string[] {
const violations = [...state.policyViolations]
if (violations.length > 0) return [...new Set(violations)].sort()
for (const facts of state.facts) {
for (const [name, rule] of expectedPackageDependencies(facts)) {
const actual = declaredSections(facts.manifest, name)
const expectedRange = workspaceRange(name)
if (rule.section === 'peer-dev') {
if (actual.length === 2
&& actual.includes('peerDependencies')
&& actual.includes('devDependencies')
&& section(facts.manifest, 'peerDependencies')[name] === expectedRange
&& section(facts.manifest, 'devDependencies')[name] === expectedRange
&& facts.manifest.peerDependenciesMeta?.[name] === undefined) continue
violations.push(
`${facts.manifestPath}: ${name} must be matching peerDependencies + devDependencies at ${expectedRange}; found ${describeSections(actual)}`,
)
continue
}
const expectedSection = rule.section
const range = section(facts.manifest, expectedSection)[name]
if (actual.length === 1
&& actual[0] === expectedSection
&& (!facts.workspaceNames.has(name) || range === expectedRange)) continue
violations.push(
`${facts.manifestPath}: ${name} (${rule.origins.join(', ')}) must be ${expectedSection}-only`
+ (facts.workspaceNames.has(name) ? ` at ${expectedRange}` : '')
+ `; found ${describeSections(actual)}`,
)
}
for (const sectionName of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'] as const) {
for (const [name, range] of Object.entries(section(facts.manifest, sectionName))) {
const expectedRange = workspaceRange(name)
if (!facts.workspaceNames.has(name) || range === expectedRange) continue
violations.push(`${facts.manifestPath}: ${sectionName}.${name} must use ${expectedRange}, found ${range}`)
}
}
for (const name of Object.keys(facts.manifest.peerDependenciesMeta ?? {})) {
if (facts.manifest.peerDependencies?.[name] === undefined) {
violations.push(`${facts.manifestPath}: peerDependenciesMeta.${name} has no matching peerDependencies entry`)
}
}
}
return [...new Set(violations)].sort()
}
/**
* Require each root-provided type package in the root devDependencies and in no workspace manifest.
* `--fix` does not remove these declarations.
* @param rootManifest - Repository root `package.json`.
* @param packages - Every workspace manifest from {@link readWorkspacePackageManifests}.
* @returns Violations in stable order.
*/
export function collectRootTypePackageViolations(
rootManifest: PackageDependencyManifest,
packages: readonly WorkspacePackageManifest[],
): string[] {
const violations: string[] = []
for (const name of ROOT_TYPE_PACKAGES) {
if (rootManifest.devDependencies?.[name] === undefined) {
violations.push(`package.json: devDependencies must declare ${name} for every workspace package`)
}
for (const pkg of packages) {
for (const sectionName of declaredSections(pkg.manifest, name)) {
violations.push(
`${pkg.manifestPath}: remove ${sectionName}.${name}; the root package.json provides it because each `
+ 'package-local link slows TypeScript JSX checking (packages/client/AGENTS.md#dependency-declaration)',
)
}
}
}
return violations.sort()
}
function deleteDependency(
manifest: PackageDependencyManifest,
sectionName: DependencySection,
name: string,
): void {
const dependencies = manifest[sectionName]
if (dependencies?.[name] === undefined) return
const retained = Object.fromEntries(Object.entries(dependencies).filter(([key]) => key !== name))
if (Object.keys(retained).length > 0) {
manifest[sectionName] = retained
return
}
switch (sectionName) {
case 'dependencies': delete manifest.dependencies; break
case 'devDependencies': delete manifest.devDependencies; break
case 'optionalDependencies': delete manifest.optionalDependencies; break
case 'peerDependencies': delete manifest.peerDependencies; break
}
}
function deletePeerMeta(manifest: PackageDependencyManifest, name: string): void {
if (manifest.peerDependenciesMeta?.[name] === undefined) return
const retained = Object.fromEntries(Object.entries(manifest.peerDependenciesMeta)
.filter(([key]) => key !== name))
if (Object.keys(retained).length > 0) manifest.peerDependenciesMeta = retained
else delete manifest.peerDependenciesMeta
}
function preferredRange(
facts: PackageDependencyFacts,
name: string,
target: ExpectedPackageDependency['section'],
): string {
if (name === CORDIS || facts.workspaceNames.has(name)) return workspaceRange(name)
const order: readonly DependencySection[] = target === 'dependencies'
? ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
: ['devDependencies', 'peerDependencies', 'dependencies', 'optionalDependencies']
const range = order.map(sectionName => section(facts.manifest, sectionName)[name]).find(value => value !== undefined)
if (range === undefined) {
throw new Error(`${facts.manifestPath}: cannot repair undeclared third-party dependency ${name}; declare its version range first`)
}
return range
}
/**
* Apply the dependency policy to one in-memory manifest.
* @param facts - Source uses and manifest to repair.
* @throws When a third-party dependency has no declared range; the manifest remains unchanged.
*/
export function repairPackageDependencyManifest(facts: PackageDependencyFacts): void {
const repairs = [...expectedPackageDependencies(facts)].map(([name, rule]) => ({
name, rule, range: preferredRange(facts, name, rule.section),